What is the default value for C++ class members

C++ClassStructDefault Value

C++ Problem Overview


What is the default values for members of a struct and members of a class in c++, and how do these rules differ (e.g. between classes/structs/primitives/etc) ? Are there circumstances where the rules about the default values differs ?

C++ Solutions


Solution 1 - C++

There are no differences between structs and classes in this regard in C++. They all are called just class types.

Members of class types have no default values in general case. In order to for a class member to get a deterministic value it has to be initialized, which can be done by

  • Default constructor of the member itself
  • Constructor initializer list of the enclosing class
  • Explicitly specified initializer for object of the enclosing class (that includes value-initialization and initialization with aggregate initializer).

Additionally, all objects with static storage duration are zero-initialized at the program startup.

Aside from the above cases, class members, once again, have no default values and will initially contain unpredictable garbage values.

Solution 2 - C++

Yeah, there is one. If you initialize an object with the default constructor and use parentheses then the POD members will be zero initialized:

someClass * p = new someClass();

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionleeeroyView Question on Stackoverflow
Solution 1 - C++AnTView Answer on Stackoverflow
Solution 2 - C++Hans PassantView Answer on Stackoverflow