Search code examples
c++oopfriend

Can a base class and a derived class of that base class have a common friend class which is a friend of both the classes?


I know that a friend class can access the private elements of a class, so I was wondering weather a derived class can use a friend class to access the private members of the base class, if the friend class is friends with both the base class and the derived class?

I am a complete beginner in programming and I have just started learning OOP in C++; I just wanted to ask this question as it came to my mind when I learned of friend functions/classes.


Solution

  • In C++, In order to grant access to private or protected members of a class, we should define a friend class or a function (or a method of another class).

    Friendship is not inherited.

    So in order to access private or protected members of a base class and derived class, from another class you should define the "another" class as friend of both base class and it s derived class.

    For the "....can a derived class use a friend class to access the private members of the base class if the friend class is friends with both the base class and the derived class?...." question.

    Friendship is not mutual. If a class Y is a friend of Y, then Y doesn’t become a friend of X automatically. So derived class can not access private members of base class using friend of base class.

    There can be a way to access private members of a base class B from derived class D by using friend class F.

    1. B should define F as a friend. (F can access private and protected members of B)
    2. F should define D as a friend.(D can access private and protected members of F)
    3. F should define methods to access and/modify all private members of B.
    4. F should define an attribute in type B and set this attribute as a parameter in constructor or in a method.
    5. D should define an attribute in type F and set itself to this attribute using the method or construtor defined in 4.

    At the end D can access all private members of B via the attribute in type F.