The working mechanism of private inheritance of a class that has a private constructor

case 1:

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

case 2:

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

In case 1: the ObjectCount constructor is private, and inheritance is private. It gives a compiler error

In case 2: the ObjectCount constructor is public, and inheritance is private. this code is ok.

Can someone explain how this happens?

+4
source share
3 answers

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

In the second case, there is no problem for Employee C'tor to call the parent ctor, since it is public.

Note that this is important, as each class must use its own parent constructor before activating it.

Private inheritance means that other classes cannot use [or see] Employee as an ObjectCount , this does not change the visibility of the ObjectCount c'tor, to which the derived class must be accessible in any case.

+3
source

Firstly, this is an understanding of what PRIVATE HERITAGE is:

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

A private constructor can only be accessed from one class. It cannot be accessed externally, not even by derived classes.

+3
source

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

+2
source

Source: https://habr.com/ru/post/1369124/


All Articles