Are default constructors created automatically for member variables?

Let's 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 member() in the initialization list of the Awesome constructor, will the member constructor be called automatically? And is this only called when I do not include member in the initialization list?

+7
source share
2 answers

From ยง 8.5

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

Update for future links . Next, the default initialization value is defined as

To initialize an object of type T by default:
- if T is a (possibly cv-qualified) class type (section 9), the default constructor for T is called (and initialization is poorly formed if T does not have an available default constructor);
- if T is an array type, each element is initialized by default;
- otherwise, no initialization is in progress.
If the program requires initialization by default, an object of type const, T, T must be a class type with a user-provided default constructor.

Further it changes from the initialized value, referring to this: -

To initialize an object of type T means:
- if T is (possibly cv-qualit) a class type (section 9) with a user-provided constructor (12.1), then the default constructor for T is called (and initialization is poorly formed if T does not have an accessible default constructor);
- if T is a (possibly cv-qualified) nonunit type class without a user-created constructor, then a zero-initialization object and, if Ts is an implicitly declared constructor by default is nontrivial, this constructor is invoked.
- if T is an array of type, then each element is initialized with a value;
- otherwise, the object is initialized to zero.

+7
source

Yes. When a variable is not listed in the initializer list, it is automatically created automatically.

The default means that if membertype is a class or struct , then it will be executed by default, if it is a built-in array, then each element will be configured by default, in the type, then initialization will not be performed (unless the Awesome object has a static or temporary storage duration in the stream). The latter case means that a member variable can (and often will) contain unpredictable garbage if an Awesome object is created on the stack or allocated on the heap.

+13
source

All Articles