Inheritance and friendship in C++


In C++, the friendship is not inherited. It means that, if one parent class has some friend functions, then the child class will not get them as friend.

In this example it will generate an error because the display() function is friend of MyBaseClass but not the friend of MyDerivedClass. The display() can access the private member of MyBaseClass.

Example

#include <iostream>
using namespace std;
class MyBaseClass {
   protected:
      int x;
   public:
      MyBaseClass() {
         x = 20;
      }
      friend void display();
};
class MyDerivedClass : public MyBaseClass {
   private:
      int y;
   public:
      MyDerivedClass() {
         x = 40;
      }
};
void display() {
   MyDerivedClass derived;
   cout << "The value of private member of Base class is: " << derived.x << endl;
   cout << "The value of private member of Derived class is: " << derived.y << endl;
}
main() {
   display();
}

Output

[Error] 'int MyDerivedClass::y' is private
[Error] within this context
raja
Published on 08-May-2019 13:11:00
Advertisements