Friend functions are not inherited by derived classes. This is because the friend
relationship is specific to the class where the friend function is declared. Here’s how it works:
When you declare a friend function in a class, you’re granting it access to the private and protected members of that specific class. This does not extend to derived classes. Each class must explicitly declare its own friends.
Consider a base class Base
and a derived class Derived
. If Base
declares a friend function, this friend function does not automatically become a friend of Derived
.
#include <iostream>
class Base {
friend void showData(Base &b, bool derived);
private:
int baseData{10};
};
class Derived : public Base {
private:
int derivedData{20};
// Note: showData is not a friend here.
};
void showData(Base &b, bool showDerived = false) {
std::cout << "\nBase data: " << b.baseData;
if (showDerived) {
std::cout << "\nDerived data: "
<< static_cast<Derived &>(b).derivedData;
}
}
int main() {
Base b;
Derived d;
showData(b, false);
showData(d, true);
}
error C2248: 'Derived::derivedData': cannot access private member declared in class 'Derived'
In this example, showData()
is a friend of Base
and can access its private members. However, it is not a friend of Derived
, so it cannot access the private derivedData
 member.
If you want a friend function to access members of both base and derived classes, you must declare it as a friend in each class:
#include <iostream>
class Base {
friend void showData(Base &b, bool derived);
private:
int baseData{10};
};
class Derived : public Base {
friend void showData(Base &b, bool derived);
private:
int derivedData{20};
};
void showData(Base &b, bool showDerived = false) {
std::cout << "\nBase data: " << b.baseData;
if (showDerived) {
std::cout << "\nDerived data: "
<< static_cast<Derived &>(b).derivedData;
}
}
int main() {
Base b;
Derived d;
showData(b, false);
showData(d, true);
}
Base data: 10
Base data: 10
Derived data: 20
By declaring showData()
as a friend in both Base
and Derived
, it can now access private members of both classes. This approach keeps the encapsulation intact while granting necessary access where needed.
Answers to questions are automatically generated and may not have been reviewed.
An introduction to the friend
keyword, which allows classes to give other objects and functions enhanced access to its members