Private Inheritance in C++

“Why Private Inheritance in C++ at all?” Concrete Classes in C++ are pretty easy to understand but what is not easy is Interface (Java style Interface), though C++ claims similar functionality using the Pure Abstract Class. Pure Abstract Class consists only Pure Virtual functions not any data (except the static one). In this way Interface (or Pure Abstract Class) refers to type of an object (instance of a class) not the Class of the object.

class Interface1{
virtual void pureVitualMethod() const=0;

class ConcreteClass1 :private Interface1{
void pureVitualMethod() const;

Now inheriting privately the Interface (as done in above code snippet) makes no use at this point of time as they will be inaccessible through the Interface’s pointer.

But class inheritance will aid you to define new objects with respect to the old class(Base class). How about inheriting it privately?

  • You cannot access derived class’s object through base class’s pointer.
  • You cannot access public or protected member function of the base class though the derived class’s object

Then the next question would be what is the use? The reasons are as follows;-

  • Pure Class inheritance (not subtyping) can be achieved via private inheritance in C++.
  • private inheritance will result in Composition (or, it exhibits the “has a” relationship rather than “is a” relationship)
  • can be necessary when you need to override a virtual function

Let see the following example, which utilizes a private inheritance,-

class HashEnvelop {
unsigned char* _mhashValue;
unsigned char* getHashValue(){
return _mhashValue;

/* Some other functions related to Hash calculations

virtual void calculateHashValue(const unsigned char* messageBytes){
// Calclates hash value for the
// specified input bytes (messageBytes)
// and stores the claculated value(in _mhashValue)

class MD5HashEnvelop: private HashEnvelop{
using HashEnvelop::getHashValue;
void calculateHashValue(const unsigned char * messageBytes){
// Calculate the hash value using MD5 algorithm
// and stores the value (in messageBytes)

Reference Readings :

  2. Design Patterns Elements of Reusable Object-Oriented Software, by Erich Gamma, Richard Helm, Ralph Johnson, John Vlissides

About yadab das
Software Developer{writing,debugging,documenting} source code

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 )

Twitter picture

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

Facebook photo

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

Google+ photo

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

Connecting to %s

%d bloggers like this: