c++structinitializationaggregate-initialization

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?


Solution

  • They are not null if you don't initialize the struct.

    Snapshot s; // receives no initialization
    Snapshot s = {}; // value initializes all members
    

    The second will make all members zero, the first leaves them at unspecified values. Note that it is recursive:

    struct Parent { Snapshot s; };
    Parent p; // receives no initialization
    Parent p = {}; // value initializes all members
    

    The second will make p.s.{x,y} zero. You cannot use these aggregate initializer lists if you've got constructors in your struct. If that is the case, you will have to add proper initalization to those constructors

    struct Snapshot {
        int x;
        double y;
        Snapshot():x(0),y(0) { }
        // other ctors / functions...
    };
    

    Will initialize both x and y to 0. Note that you can use x(), y() to initialize them disregarding of their type: That's then value initialization, and usually yields a proper initial value (0 for int, 0.0 for double, calling the default constructor for user defined types that have user declared constructors, ...). This is important especially if your struct is a template.