Reputation: 11651
Suppose I have the following class:
class dog
{
public:
int age;
int bun;
};
Now this statement
dog d = {12,5}
would initialize age
to 12 and bun
to 5
Now if the class above has a parameter-less constructor the above statement initialization does not work. I would appreciate it if someone could explain why that happens?
Upvotes: 1
Views: 87
Reputation: 476950
The syntax dog d = { 12, 5 };
is aggregate initialization when the class dog
is an aggregate. A user-provided constructor prevents a class from being an aggregate; cf. C++11 8.5.1/1:
An aggregate is an array or a class (Clause 9) with no user-provided constructors (12.1), no brace-or-equal-initializers for non-static data members (9.2), no private or protected non-static data members (Clause 11), no base classes (Clause 10), and no virtual functions (10.3).
(I believe that the next revision of C++ will permit brace-or-equals initializers in aggregates.)
Upvotes: 4