Can a friend class object access the methods of the host class?

Suppose we have a class A:

class A{
    int a_;
public:
    friend class B;
    A(int a):a_(a){}
    int getA(){ return a_;}
    void setA(int a){a_ = a;}
    void print(int x){cout << x << endl;}
};

and another class B:

class B{
    int b_;
public:
    B(int b):b_(b){}
    void setB(int b){b_ = b;}
    int getB(){return b_;}
    //friend void A::print(int x);
};

How to use a method of class A like print() using an object of class B?

//main.cpp
B b1(10);
b1.print(b1.getB());

>Solution :

How to use a method of class A like print() using an object of class B?

B isn’t related to A in any way so you can’t. The only thing you’ve done by adding a friend declaration is that you’ve allowed class B(or B‘s member functions) to access private parts of class A through an A object. Note the last part of the previous sentence. We still need an A object to be able to call A::print().

That is, friendship doesn’t mean that you can directly(without any A object) access A‘s private members.

Leave a Reply