What is the point of a C++ implicit default constructor?

十年热恋 提交于 2019-12-10 19:24:38

问题


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?


回答1:


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).




回答2:


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).




回答3:


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.



来源:https://stackoverflow.com/questions/39181981/what-is-the-point-of-a-c-implicit-default-constructor

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!