19

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?

Lanaru
  • 9,421
  • 7
  • 38
  • 64
  • possible duplicate of [What is the default value for C++ class members](http://stackoverflow.com/questions/2614809/what-is-the-default-value-for-c-class-members) – FailedDev Aug 16 '12 at 18:23
  • depends on `membertype` but usually yes. – AJG85 Aug 16 '12 at 18:33

2 Answers2

22

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.

Ralph Tandetzky
  • 22,780
  • 11
  • 73
  • 120
10

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.

perilbrain
  • 7,961
  • 2
  • 27
  • 35