Consider a code example showing what will be allowed (or not) using different levels of inheritance:
class BaseClass {}; void freeStandingFunction(BaseClass* b); class DerivedProtected : protected BaseClass { DerivedProtected() { freeStandingFunction(this); // Allowed } };
DerivedProtected can go to freeStandingFunction because it knows that it comes from BaseClass .
void freeStandingFunctionUsingDerivedProtected() { DerivedProtected nonFriendOfProtected; freeStandingFunction(&nonFriendOfProtected); // NOT Allowed! }
An alien (class, function, whatever) cannot pass DerivedProtected to freeStandingFunction because inheritance is protected and therefore not visible outside derived classes. The same goes for private inheritance.
class DerivedFromDerivedProtected : public DerivedProtected { DerivedFromDerivedProtected() { freeStandingFunction(this); // Allowed } };
A class derived from DerivedProtected can say that it inherits from BaseClass , so it can go to freeStandingFunction .
class DerivedPrivate : private BaseClass { DerivedPrivate() { freeStandingFunction(this); // Allowed } };
The DerivedPrivate class DerivedPrivate knows that it comes from BaseClass , so it can go to freeStandingFunction .
class DerivedFromDerivedPrivate : public DerivedPrivate { DerivedFromDerivedPrivate() { freeStandingFunction(this); // NOT allowed! } };
Finally, the non-friend class, located further down the inheritance hierarchy, cannot see DerivedPrivate inheriting from BaseClass , so it cannot go to freeStandingFunction .
Daniel gallagher
source share