Private Inheritance

In private inheritance, the base class public access members are still public access in the derived class. Therefore the derived class still can call the base class functions and access its public data. But the user who instantiates the derived class, cannot access the public member of the base class, hence private inheritance.

  • Public inheritance is a “is-a” relationship.
  • Private inheritance is a “implemented-in-terms-of” relationship.

A useful example, is I like .NET string class and like a C++ string class with the same C# methods but I do not want to reimplement from scratch, so I derived from std::wstring with private inheritance to make use of its functionality, so that user of my string class cannot access the base class’s std::wstring functions to avoid the confusion and I also do not want the user to be exposed to underlying std::wstring details.

class MyString : private std::wstring

There is an excellent blog about this topic: C++ Tutorial: Private Inheritance.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: