Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

//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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading