Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Definition of friend class and accessor sections

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
{};
like image 685
Zamfir Avatar asked Apr 07 '11 03:04

Zamfir


People also ask

What is meant by a friend class?

Friend Class A friend class can access private and protected members of other class in which it is declared as friend. It is sometimes useful to allow a particular class to access private members of other class.

What is a friend class in C?

A friend class in C++ can access the private and protected members of the class in which it is declared as a friend. A significant use of a friend class is for a part of a data structure, represented by a class, to provide access to the main class representing that data structure.

How do you define a Friends class in Java?

friend function of a class is defined outside that class' scope but it has the right to access all private and protected members of the class. Even though the prototypes for friend functions appear in the class definition, friends are not member functions.

What is friend function and class?

A friend function is a function that is specified outside a class but has the ability to access the class members' protected and private data. A friend can be a member's function, function template, or function, or a class or class template, in which case the entire class and all of its members are friends.


2 Answers

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.

like image 190
Alok Save Avatar answered Nov 26 '22 17:11

Alok Save


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).

like image 24
iammilind Avatar answered Nov 26 '22 15:11

iammilind