devxlogo

Declaring a Member Function as a Friend of Another Class

Declaring a Member Function as a Friend of Another Class

Although you can declare an entire class a friend of another class, like this:

 class A{ friend class B; //B has  access  to every member of A //..};

However, in most cases, only one or two member functions of B need such unrestricted access to A. To avoid indiscriminate access, you can declare individual member functions of B as friends. To declare a member function as a friend, simply provide its prototype followed by the keyword friend. For example:

 class B; // fwd declaration required; A::f() takes B&struct A{ int f(B&);};struct B{ friend int A::f(B&); // a member function friendprivate: int x;};int A::f(B& b) { return b.x; // access private member of b}int main(){ A a; B b; a.f(b); // access a private member of b}

devx-admin

Share the Post: