Initializing a struct to zeroes

I know you can initialize an array to all zeroes like so:

int a[10] = { 0 };

And, as another example, this would initialize the first element to 1 and the rest to zero:

int a[10] = { 1 };

But can you do the same thing with a struct?

1
2
3
4
5
6
struct Thing {
    int a, b, c;
};

Thing thing1 = { 0 };  // all members 0
Thing thing2 = { 1 };  // Member a = 1, b = c = 0 

I've tested it and it seems to work, but is it guaranteed to work by the standard? (I'm trying to read that thing, but OUCH, what a document! It hurts my head.)
Don't use that initialization style on C++, use a constructor:
1
2
3
4
5
6
7
struct Thing {
    int a, b, c;
    Thing ( int A=0, int B=0, int C=0 ) : a(A), b(B), c(C){}
};

Thing thing1;//a=b=c=0
Thing thing2 ( 1 );//a=1 b=c=0 


I was asking what the standard says about this exact situation:

1
2
3
4
5
6
struct Thing {
    int a, b, c;
};

Thing thing1 = { 0 };  // all members 0
Thing thing2 = { 1 };  // Member a = 1, b = c = 0 


Is it guaranteed to work as indicated in the comments?
No, it can't.

Consider if the struct contained an int and a std::vector().
It seems to work.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
#include <iostream>
#include <vector>

struct Thing {
    int a, b, c;
    std::vector<int> v;
};

int main() {
    Thing x = { 1, 2, 3 };
    std::cout << x.a << x.b << x.c << '\n';
    std::cout << x.v.size() << '\n';
    x.v.push_back( 456 );
    std::cout << x.v[0] << '\n';
}


Topic archived. No new replies allowed.