Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Default constructors C++

Tags:

c++

Lets say I have this class:

class X {
public:
    int x;
};

I saw that if I create an instance of X locally, x will not be initialize to 0, only if I create it globally.
Does this mean that the default constructor isn't synthesized by the compiler(I doubt it) for objects created localy or it will be synthesized but not zero out x value, if this is the case why is that ?

like image 690
Adrian Avatar asked May 09 '11 20:05

Adrian


2 Answers

Constructors in C++ don't generally initialize members to 0. You have to explicitly initialize members with a value.

The reason that in the global case the memory is zero, is because static memory gets initialized to zero before anything else happens to it. In your case, the implicitly generated default constructor gets called afterwards, which does not touch the memory for member X.

See also this answer from Derek: Is global memory initialized in C++?

Note, however, that default constructors for structured, non-POD members (classes and structs) do automatically get called by the default constructor. It's just the POD members that are left alone by default.

like image 194
TheFogger Avatar answered Oct 20 '22 04:10

TheFogger


X gets a synthesised constructor, but synthesised constructors do not zero-initialise primitives.

like image 2
Lightness Races in Orbit Avatar answered Oct 20 '22 03:10

Lightness Races in Orbit