AlwaysLearning
AlwaysLearning

Reputation: 8011

Why would a class with inherited constructors get a synthesized default constructor as well?

C++ Primer (5th edition) on page 629 states:

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

What is the reasoning behind this rule?

Upvotes: 6

Views: 273

Answers (2)

Paolo M
Paolo M

Reputation: 12757

I think that quote can be misgiving. The following, 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 one! I said public! Actually, the error message from gcc is:

'Derived::Derived()' is implicitly deleted because the default definition would be ill-formed

So, what the author means is that if a Derived class inherit constructors from a Base class, a default constructor for Derived will be provided, because it may have to default initialize Derived's data member that can't be initialized from inherited constructors, because they even don't know of their existence.

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

Upvotes: 6

Serge Rogatch
Serge Rogatch

Reputation: 15030

If the base class does not contain a constructor without parameters, then the compiler would not be able to generate a default constructor for the derived class because it needs the missing arguments for the constructors of the base class. However, if base class contains a default constructor or a constructor that does not take any parameters, then a default constructor for the derived class can be generated with the usual purpose of calling constructors of the member variables. The purpose is the convenience not to write an empty constructor yourself if the constructor doesn't do anything special.

Upvotes: 2

Related Questions