sukumar
sukumar

Reputation: 377

Working mechanism of private inheritance of a class having private constructor

case 1:

class ObjectCount {
private:
    ObjectCount(){}
};

class Employee : private ObjectCount {};

case 2:

class ObjectCount {
public:
    ObjectCount(){}
};

class Employee : private ObjectCount {};

In case1: ObjectCount constructor is private and inheritance is private . It gives compiler error

In case2: ObjectCount constructor is public and inheritance is private . this code is ok.

Can anyone explain how is it happening?

Upvotes: 5

Views: 1960

Answers (3)

Miketelis
Miketelis

Reputation: 138

First thing is understanding what is PRIVATE INHERITANCE:

Private Inheritance is one of the ways of implementing the has-a relationship. With private inheritance, public and protected members of the base class become private members of the derived class. That means the methods of the base class do not become the public interface of the derived object. However, they can be used inside the member functions of the derived class.

The Private Constructor can only be accessed from inside the same class. It cannot be accessed from the outside, not even by the derived classes.

Upvotes: 3

Feanor
Feanor

Reputation: 670

This is because the derived class does not have access to any base constructor when the base constructor is defined 'private' so there is no way for the derived class to call any base class constructor. In the second case, public methods (in this case the constructor) are inherited so there is no problem.

Upvotes: 2

amit
amit

Reputation: 178421

In first case, the Employee C'tor cannot invoke its parent (ObjectCount) C'tor, because it is private.

In the 2nd case, there is no problem for the Employee C'tor to invoke the parent's ctor, since it is public.

Note that this is important since every class must use its parent constructor before activating its own.

The private inheritence means that other classes cannot use [or see] Employee as a ObjectCount, it doesn't change the visibility of ObjectCount's c'tor, which must be accessable by the derived class in any case.

Upvotes: 3

Related Questions