简体   繁体   中英

implicitly declared default constructor

I am confused with the following statement.

From the specification:

Before the implicitly-declared default constructor for a class is implicitly defined, all the implictly-declared default constructors for its base classes and its non static data members shall have been implicitly defined.

What i understand is :

implicitly declared default constructor is implicitly defined when the object is created.

What does the above statement means?. if base class contains explicit default constructor, then the derived class can not have a implicit default constructor?. Kindly clarify, it could be nice if someone provides piece of sample code.

The statement means that when the compiler must provide a definition for an implicitly declared default constructor (ie when such constructor is odr-used ), before the definition of the current constructor the compiler must ensure that all members can be default constructed, and for that it might need to implicitly define any implicitly declared default constructor of the members.

For an example:

struct A { int x; };    
struct B { A a; };      // [1]
int main() {
   B b;                 // [2]
}

The definition of the variable b in [2] is an odr-use of the implicitly declared constructor for B , but before the compiler implicitly defines B::B() , because it has a member of type A declared in [1], it needs to implicitly define A::A() . The reason being that B::B() will odr-use A::A() in it's initialization list.

Assume you have classes Base and Derived (which is derived from base).

Let's assume both of them have implicitly declared default constructors. When you will create an object of Derived class, the following will happen. First , implicitly-declared default constructor for the Base class will be defined. After that, the same will happen with the implicitly-declared constructor for the Derived class.

This totally makes sense, because when you create the object of Derived class, the constructor for the Base class gets called first. If it will not be defined by that time, well, something bad will probably happen.

The same things apply to any class members that have such constructors: those are defined before the class' own constructor will get defined.

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