[c++] Are members of a C++ struct initialized to 0 by default?

I have this struct:

struct Snapshot
{
    double x; 
    int y;
};

I want x and y to be 0. Will they be 0 by default or do I have to do:

Snapshot s = {0,0};

What are the other ways to zero out the structure?

This question is related to c++

The answer is


With POD you can also write

Snapshot s = {};

You shouldn't use memset in C++, memset has the drawback that if there is a non-POD in the struct it will destroy it.

or like this:

struct init
{
  template <typename T>
  operator T * ()
  {
    return new T();
  }
};

Snapshot* s = init();

In C++, use no-argument constructors. In C you can't have constructors, so use either memset or - the interesting solution - designated initializers:

struct Snapshot s = { .x = 0.0, .y = 0.0 };

I believe the correct answer is that their values are undefined. Often, they are initialized to 0 when running debug versions of the code. This is usually not the case when running release versions.


Since this is a POD (essentially a C struct) there is little harm in initialising it the C way:

Snapshot s;
memset(&s, 0, sizeof (s));

or similarly

Snapshot *sp = new Snapshot;
memset(sp, 0, sizeof (*sp));

I wouldn't go so far as to use calloc() in a C++ program though.


No, they are not 0 by default. The simplest way to ensure that all values or defaulted to 0 is to define a constructor

Snapshot() : x(0), y(0) {
}

This ensures that all uses of Snapshot will have initialized values.


Move pod members to a base class to shorten your initializer list:

struct foo_pod
{
    int x;
    int y;
    int z;
};

struct foo : foo_pod
{
    std::string name;
    foo(std::string name)
        : foo_pod()
        , name(name)
    {
    }
};

int main()
{
    foo f("bar");
    printf("%d %d %d %s\n", f.x, f.y, f.z, f.name.c_str());
}

In general, no. However, a struct declared as file-scope or static in a function /will/ be initialized to 0 (just like all other variables of those scopes):

int x; // 0
int y = 42; // 42
struct { int a, b; } foo; // 0, 0

void foo() {
  struct { int a, b; } bar; // undefined
  static struct { int c, d; } quux; // 0, 0
}