开发者

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开发者_JS百科 how is it happening?


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.


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.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜