“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{
public:
virtual void pureVitualMethod() const=0;
};
class ConcreteClass1 :private Interface1{
public:
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 {
private:
unsigned char* _mhashValue;
public:
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{
public:
using HashEnvelop::getHashValue;
void calculateHashValue(const unsigned char * messageBytes){
// Calculate the hash value using MD5 algorithm
// and stores the value (in messageBytes)
}
};
Reference Readings :
- http://www.cprogramming.com/tutorial/private.html
- Design Patterns Elements of Reusable Object-Oriented Software, by Erich Gamma, Richard Helm, Ralph Johnson, John Vlissides
- http://www.parashift.com/c++-faq-lite/private-inheritance.html