1

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?

1 Answer 1

4

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.)

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks. That explained it. Marked as answer

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.