Why will a class with inherited constructors also get a synthesized default constructor?

C ++ Primer (5th Edition) on page 629:

A class containing only inherited constructors will have a synthesized default constructor.

What is the reason for this rule?

+6
source share
2 answers

I think the quote may be wrong. Below, for example, will not compile:

struct Base{ Base(int){} }; struct Derived : Base{ using Base::Base; }; int main() { Derived d; // error: Derived has no public default ctor!!! } 

Derived contains only inherited constructors, but it does not have a public default value! I told the public! Actually, the error message from gcc :

'Derived :: Derived ()' is implicitly deleted as the default definition will be poorly formed

So, what the author means is that if the Derived class inherits constructors from the Base class, a default constructor for Derived will be provided, because it may need to initialize the default Derived element, which cannot be initialized from inherited constructors, because they donโ€™t even know about their existence.

Finally, in my example, the compiler implicitly removed the default ctor for Derived, because no one explicitly defined it. But if you add the default ctor to Base, a synthesized default ctor for Derived will be created.

+6
source

If the base class does not contain a constructor without parameters, the compiler cannot create a default constructor for the derived class because it needs missing arguments for the base class constructors. However, if the base class contains a default constructor or a constructor that does not accept any parameters, then the default constructor for the derived class can be generated for the usual purpose of invoking member variable constructors. The goal is the convenience of not writing an empty constructor yourself if the constructor does nothing special.

+2
source

All Articles