Reputation: 14408
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.
Upvotes: 2
Views: 3753
Reputation: 208323
The statement means that when the compiler must provide a definition for an implicitly declared default constructor (i.e. 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.
Upvotes: 4
Reputation: 29966
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.
Upvotes: 2