Denis
Denis

Reputation: 3092

Multiple inheritance and inaccessible default constructor

Why it works

class CL1{};
class CL2:private virtual CL1{};
class CL3:private virtual CL1{};

class CL4:public CL2,public CL3
{
public:
    CL4():CL2(),CL3(){}
};

int main()
{
    CL4 cl4;
    return 0;
}

, but if I call constructor of virtual base class explicitly

CL4():CL1(),CL2(),CL3(){}

, then it does not work? P.S. Compiler is https://ideone.com/HuHlCB

Upvotes: 2

Views: 508

Answers (3)

Prateek
Prateek

Reputation: 51

As CL4 is derived from CL3,CL2, so CL1 constructor of CL1 class cannot be accessed explicitly from CL4. Had it been member function, i.e member functions of base class can be accessed from derived class, constructors cannot because CL4 class cannot be converted to CL1.

Upvotes: 1

Rakib
Rakib

Reputation: 7625

CL2 and CL3 inherits CL1 privately, so everything in CL1 (including constructor) becomes private in these derived classes. The former case works because CL1::CL1() is called by the constructor of the derived classes. But you can not explicitly call it, because for your inheritance chain, you access the constructor via one of the derived classes (either CL2 or CL3), but it is private in that classes, only other class members can access it.

Why it works?

Because CL2 and CL3 can access their private members (including base class constructors)

Why explicit call does not work?

Because CL4 can not access CL2's and CL3's private members.

Upvotes: 3

Dennis
Dennis

Reputation: 3741

It is because you are using private inheritance from CL2/3 to CL1. This means that they are "implemented in terms of" CL1, not that they are CL1 (which is the meaning of public inheritance). You cannot convert the class CL2 into a CL1, and so CL4 is NOT a CL1 also.

You can access the members of CL1 only in CL2 as if they were private members.

Upvotes: 2

Related Questions