Are default constructors called automatically for member variables?

两盒软妹~` 提交于 2019-12-18 11:27:27

问题


Say I have this class:

//Awesome.h
class Awesome
{
    public:
        Awesome();
    private:
        membertype member;
}

//Awesome.cpp
#include "Awesome.h"

Awesome::Awesome()
:member()
{
}

If I omit the member() in the initialization list of the constructor of Awesome, will the constructor of member be called automatically? And is it only called when I don't include member in the initialization list?


回答1:


From § 8.5

If no initializer is specified for an object, the object is default-initialized; if no initialization is performed, an object with automatic or dynamic storage duration has indeterminate value. [ Note: objects with static or thread storage duration are zero-initialized, see 3.6.2. —end note ]

Update for future references: Further the meaning of default initialized is defined as

To default-initialize an object of type T means:
if T is a (possibly cv-qualified) class type (Clause 9), the default constructor for T is called (and the initialization is ill-formed if T has no accessible default constructor);
— if T is an array type, each element is default-initialized;
— otherwise, no initialization is performed.
If a program calls for the default initialization of an object of a const-qualified type T, T shall be a class type with a user-provided default constructor.

Further it varies from value initialized referring this:-

To value-initialize an object of type T means:
— if T is a (possibly cv-qualified) class type (Clause 9) with a user-provided constructor (12.1), then the default constructor for T is called (and the initialization is ill-formed if T has no accessible default constructor);
— if T is a (possibly cv-qualified) non-union class type without a user-provided constructor, then the object is zero-initialized and, if T’s implicitly-declared default constructor is non-trivial, that constructor is called.
— if T is an array type, then each element is value-initialized;
— otherwise, the object is zero-initialized.




回答2:


Yes. When a variable is not given in the initalizer list, then it is default constructed automatically.

Default contruction means, that if membertype is a class or struct, then it will be default contructed, if it's a built-in array, then each element will be default constructed and if it's a build-in type, then no initialization will be performed (unless the Awesome object has static or thread-local storage duration). The last case means that the member variable can (and often will) contain unpredictable garbage in case the Awesome object is created on the stack or allocated on the heap.



来源:https://stackoverflow.com/questions/11993134/are-default-constructors-called-automatically-for-member-variables

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