简体   繁体   中英

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?

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM