Search code examples
c++constructorheader

Are default constructors called automatically for member variables?


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?


Solution

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