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}
See also  Monetize TikTok For Your Business

About Our Editorial Process

At DevX, we’re dedicated to tech entrepreneurship. Our team closely follows industry shifts, new products, AI breakthroughs, technology trends, and funding announcements. Articles undergo thorough editing to ensure accuracy and clarity, reflecting DevX’s style and supporting entrepreneurs in the tech sphere.

See our full editorial policy.

About Our Journalist