History of the issue:
In earlier versions of C++, all class members had to be initialized either in the constructor's initialization list or in the body of the constructor. With the advent of C++11, it became possible to initialize non-static class members directly at their definition — this significantly improved readability and reduced the likelihood of errors with uninitialized variables.
Problem:
The absence of default initialization led to non-obvious behavior for developers, especially with the emergence of new constructors. There was no guarantee that class members would always be initialized. The beauty and novelty of the approach lie in the reduction of boilerplate code.
Solution:
Inline initialization sets a default value for a class member if it was not explicitly initialized in the constructor’s initialization list.
Example code:
class Widget { int value = 42; std::string name{"default"}; public: Widget() {} Widget(int v) : value(v) {} };
Key features:
Will the value from inline initialization be used if the member is specified in the constructor's initialization list?
No, the value from the constructor’s initialization list will be used. Example:
class Test { int a = 10; public: Test(int x) : a(x) {} }; Test t(42); // a == 42
Is it possible to inline-initialize static class members?
No, only non-static. Static class members are initialized separately outside the class.
Can expressions be used for inline initialization of class members?
For simple members — yes (for example, a constructor call or literal). For complex computations, use a function or initialization in the constructor.
The team added a new constructor but forgot to initialize a field. It remained with an uninitialized value. A crash occurred when accessing the variable.
Pros:
Cons:
Inline initialization was applied to all class fields. New constructors did not require explicit initialization, reducing boilerplate code and errors.
Pros:
Cons: