Definition of friend class and accessor sections
Asked Answered
C

4

5

When defining a class as a friend class, does it matter in which accessor section the definitions is placed, and if so does that change the members the friend has access to?

class aclass
{
private:
   // friend bclass;

public:
   // friend bclass;

protected:
   // friend bclass;
};

class bclass
{};
Collegian answered 7/4, 2011 at 3:26 Comment(0)
V
3

Access specifiers do not apply to friend function/Class
You can declare the Friend Function or Class under any Access Specifier and the Function/Class will still have access to all the member variables(Public,Protected & Private) of that Class.

Veldaveleda answered 7/4, 2011 at 4:35 Comment(0)
O
2

Once you place friend class/function inside a given class (say 'aclass') anywhere. It will have access to all defined members of the class (irrespective of public/private/protected); for example:

class aClass
{
public: int pub;  void fun1() {}
protected: int pro; void fun2() {}
private: int pri;  aClass(const aClass& o);  
  friend void outsider ();  
};

Friend function outsider() can access pub, pro, pri, fun1, fun2; but not aClass copy constructor in this case (if it's not defined anywhere).

Oecd answered 7/4, 2011 at 3:48 Comment(0)
K
1

Friend functions aren't placed inside any accessors by convention, because by definition they aren't part of the class. You might do something like this:

class Elephants
{
 //friend void notAMemberFuncion(argument 123);

public:
// member functions;

protected:
// data members;
};
Kithara answered 7/4, 2011 at 3:38 Comment(1)
read the question, not talking about friend functions but rather friend classes.Collegian
Y
1

The friend class/function can access all the private/protected/public members of class, which access section the friend class/function is placed doesn't make any difference. It's suggested to put friend class/function in the public section, because friends is part of the class interface.

Youngling answered 7/4, 2011 at 3:57 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.