In C++ ,  constructors , destructor, and base class’s friend are not inherited to derived class. it means if  class A has friend function and class B is derived class then in this case the friend function declared in base class A does not become friend of class B.

Try to compile below program. we will get error like. this will not compile because print() function which is friend function in class A is not inheritable in derived class B.

#include<iostream>
using namespace std;

class A {
private:
	int a;
	friend void print();
};

class B: public A {
private:
	int b;
	//    friend void print();
};

void print() {
	B b_obj;
	cout << b_obj.b << endl;
}

int main() {
	return 0;
}

 

Some interview question ask during interview:

Why does C++ not allow inherited friendship?
Why does constructor and destructor are not inherited?
Are static members are inherited in c++?



Related Contents to follow