What is the default value for C ++ class members

What are the default values ​​for structure members and class members in C ++ and how do these rules differ (e.g. between classes / structures / primitives, etc.)? Are there situations where the rules regarding the default values ​​are different?

+44
c ++ struct class default-value
Apr 10 '10 at 20:14
source share
2 answers

In C ++, there is no difference between structures and classes. All of them are simply called class types.

Members of class types do not have default values ​​in the general case. For a class member to get a deterministic value, it must be initialized, which can be done

  • The default constructor of the element itself
  • List of wrapper class constructor initializers
  • The explicit initializer for the object of the incoming class (which includes initialization initialization initialization and initialization).

In addition, all objects with a static storage duration are initialized to zeros when the program starts.

In addition to the above cases, class members again have no default values ​​and will initially contain unpredictable garbage values.

+41
Apr 10 2018-10-10T00:
source share

Yes, there is one. If you initialize the object using the default constructor and use parentheses, then the POD members will be initialized to zero:

someClass * p = new someClass(); 
+14
Apr 10 2018-10-10T00:
source share



All Articles