Reputation: 3089
A implicit default constructor has an empty body and an empty initializer list (primitive types undefined, and the default constructor is called for user defined types).
This post says
MyClass *c = new MyClass();
does indeed do a member-wise value-initialization, but what is the point of calling the default constructor when doing
MyClass c;
?
Is the implicit default constructor called, to ensure that the default constructors for user defined types (which might have non-trivial default constructors) are called?
Update
Seems that after the compiler-generated implicit default constructor is called, the object might not be consistently instantiated, i.e. primitive types undefined, and user defined types might (or might not be) in a known state depending on if the programmer provided default constructors.
Why then does the compiler generate an implicit default constructor which when called might instantiate an object in an unknown state?
Upvotes: 3
Views: 1286
Reputation: 3089
I read in Wikipedia Virtual Method Table
As such, the compiler must also generate "hidden" code in the constructor of each class to initialize a new objects' vpointer to the address of its class's vtable.
Perhaps that is one reason for having a default implicit constructor - when there is a class hierarchy with virtual methods, each instance needs the vpointer setup correctly.
Upvotes: 0
Reputation: 118300
The point of the implicit default constructor is the same point as of any other constructor.
Something needs to construct every instance of a given class. The class instance is not going to appear out of thin air, by itself. Something, somewhere, has the job of constructing the object.
If an explicit constructor is not declared, an implicit default constructor gets automatically defined, that default-constructs the class's superclasses, and any class members.
Here, "default-constructs" also includes the "do nothing" option, if the class member is a primitive type with no explicit constructor. So, in the end, the implicit default constructor may end up doing nothing. But it is still defined, if an explicit constructor is not specified (and if the implicit default constructor is not explicitly deleted, of course).
Upvotes: 5
Reputation: 249123
Whether you do this:
MyClass c;
or this:
MyClass *c = new MyClass();
You are invoking the default constructor.
You're right that the implicit default constructor does leave primitive types like int
and double
uninitialized. But it does initialize any other member variables, such as strings, by calling their default constructors (implicit or explicit).
Upvotes: 4