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

Output

[Error] 'int MyDerivedClass::y' is private
[Error] within this context
Updated on: 2019-07-30T22:30:26+05:30

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements