There is lots of difference between public and private inheritance in C++. Both are different concepts all together. To put it in one word, public inheritance is Interface inheritance where as private inheritance is Implementation inheritance.
Now, what's this interface inheritance and implementation inheritance??
Interface inheritance: a method of creating a subtype of an existing class for purposes of setting up dynamic binding, (Is-A relationship)
e.g.
Class Shape { ... };
Class Circle : public Shape { ... };
Implementation inheritance: a method of reusing an implementation to create a new class type.
e.g.
class Vector { ... };
class Stack : private Vector { ...};
Stack is inheriting from class Vector. A Stack is not really a subtype or specialization of Vector.
In this case, inheritance makes implementation easier, since there is no need to rewrite and debug existing code.
This is called using inheritance for reuse i.e., a pseudo-Has-A relation.
Lets take one example and try put, how different for the user of this inheritance.
class Base {
public:
Base() { }
~Base() { }
virtual void Display() { }
};
class Derived : /*public*/ Base {
public:
Derived() { }
~Derived() { }
void Display() { }
};
void TestPrivateInheritance() {
Base* pBase = new Derived();
pBase->Display();
delete pBase;
}
For your surprise, you will get an error !
error C2243: 'type cast' : conversion from 'class Derived *' to 'class Base *' exists, but is inaccessible
Its as good as, Derived is not "is-a" of Base. Its kind of Has-a ( pseudo-Has-A ). So, you can not access Derived as if its of Base type, which is possible ( and of course main goal) of public inheritance. You can check it out by removing comments around public in inheritance mode.
So, we cannot achieve polymorphism or dynamic binding using private inheritance.
This behavior is same in case of protected inheritance. That is, it behaves similarly as private inheritance behaves.
C++ Design/Coding tips - Part 7