Friend Function and Friend Class in Inheritance
Friendship and inheritance are separate ideas in C++.
The most important rule:
Friendship is not inherited.
If a function is a friend of a base class, it does not automatically become a friend of the derived class.
Friend Function Example
#include <iostream>
using namespace std;
class Derived;
class Base {
private:
int baseSecret = 10;
friend void showSecrets(const Base& base, const Derived& derived);
};
class Derived : public Base {
private:
int derivedSecret = 20;
friend void showSecrets(const Base& base, const Derived& derived);
};
void showSecrets(const Base& base, const Derived& derived) {
cout << "Base secret: " << base.baseSecret << endl;
cout << "Derived secret: " << derived.derivedSecret << endl;
}
int main() {
Base base;
Derived derived;
showSecrets(base, derived);
return 0;
}
What To Notice
showSecrets() is declared as a friend in both classes.
If it were only friend of Base, it could access Base private data but not Derived private data.
Friend Class Rule
Friend class relationship is also not inherited.
If Helper is a friend of Base, it does not automatically become a friend of Derived.
The derived class must explicitly declare:
friend class Helper;
if Helper needs access to derived private data.
Friendship Is Not Symmetric
If A is friend of B, that does not mean B is friend of A.
Friendship Is Not Transitive
If A is friend of B, and B is friend of C, that does not mean A is friend of C.
Viva Answer
Friendship is not inherited in C++. A friend of a base class does not automatically become a friend of a derived class. Friendship is also not symmetric and not transitive. If access is needed, friendship must be declared explicitly in each class.
Quick Check
- Is friendship inherited?
- If a function is friend of
Base, can it access private data ofDerivedautomatically? - Is friendship symmetric?