Possible Duplicate:
What are the differences between struct and class in C++
I used to think that the only differences between C++ classes were the private-by-default class member access modifiers and the laid-out-like-C guarantee.
It turns out I was wrong, because this code doesn't compile:
class { int value; } var = { 42 };
whereas this does:
struct { int value; } var = { 42 };
I can't figure out why there's a difference, but there apparently is in Visual C++ 2008:
error C2552:
'var'
: non-aggregates cannot be initialized with initializer list
So, yes, I will ask a many-times-over duplicate question (hopefully without duplicate answers!):
Of course, feel free to close this if you find that I've missed something in the other questions -- I certainly might have. But I didn't see this being discussed in any of the answers, so I thought I'd ask.
You can use {}
initializer for aggregates only1 and the first one is not an aggregate, as it has one private
data member.
The Standard says in section §8.5.1/1,
An aggregate is an array or a class (clause 9) with no user-declared constructors (12.1), no private or protected non-static data members (clause 11), no base classes (clause 10), and no virtual functions (10.3).
1. Well, I meant, in C++03, you can use {}
for aggregates ONLY, but in C++11, you can use {}
even with non-aggregates (if the non-aggregate class is properly implemented to handle this).
Also see this for detail answer (on {}
initializer):
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With