Why non-static data member initialization is important
C++11 default member initializers let you initialize class members where they are declared, so every constructor gets the same defaults.
Before the Modern C++ approach (C++11), we initialized our class something like this.
#include <iostream>
class MyClass {
int data1;
int data2;
public:
MyClass(){
this->data1 = 0;
this->data2 = 0;
}
};
But Modern C++ gives us this option.
#include <iostream>
class MyClass {
int data1 {0};
int data2 {0};
public:
MyClass(){
//other codes
}
};
Initializing with simple curly brackets at the declaration is called a default member initializer. It doesn’t create a separate method. The compiler uses it in every constructor that doesn’t initialize that member in its own initializer list, and it runs before the constructor body. As a result, we don’t have to do anything for other alternative constructors.
class MyClass {
int data1 {0};
int data2 {0};
public:
MyClass() = default; // data1 = 0, data2 = 0
MyClass(int d) : data1{d} {} // data1 = d, data2 = 0
};
With the old style, if you add a new constructor and forget one of the assignments, that member stays uninitialized and reading it is undefined behavior. With a default member initializer, there is only one place to forget.