Browse DevX
Sign up for e-mail newsletters from DevX

Tip of the Day
Home » Tip Bank » C++
Language: C++
Expertise: Intermediate
Dec 11, 2001



Building the Right Environment to Support AI, Machine Learning and Deep Learning

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 friend
 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
Danny Kalev
Comment and Contribute






(Maximum characters: 1200). You have 1200 characters left.



Thanks for your registration, follow us on our social networks to keep up-to-date