Home > other >  Can a friend class object access the methods of the host class?
Can a friend class object access the methods of the host class?

Time:10-23

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());

CodePudding user response:

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.

CodePudding user response:

Short answer: No, a friend class's object cannot access the methods of the class of which it is a friend. It can only access the data members(private or protected).

  • Related