Initialization of non-aggregate type with an initializer list

Aug 6, 2012 at 5:51pm
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
class monthData {
    int days;
    char name[12];
};

const monthData months [] =
{
    { 0, " " },
    { 31, "January" },
    { 28, "February" },
    { 31, "March" },
    { 30, "April" },
    { 31, "May" },
    { 30, "June" },
    { 31, "July" },
    { 31, "August" },
    { 30, "September" },
    { 31, "October" },
    { 30, "November" },
    { 31, "December" }
};


I copied this code from my C++ book by Russel Winder.

When I compile it I get the error: "Initialization of non-aggregate type 'const monthData' with an initializer list".

Can anyone please tell me how to fix it?
Last edited on Aug 6, 2012 at 5:53pm
Aug 6, 2012 at 6:15pm
What compiler are you using?
Aug 6, 2012 at 6:27pm
I couldn't find the exact name of the compiler but I'm using the default Xcode compiler in Mac OS X 10.8. I actually think it's GCC.
Aug 6, 2012 at 6:46pm
That code is erroneous.

Replace that "class" with "struct", or insert a public: on the first line of the class to make it compile in all compilers (aggregates cannot have private members).

PS: Are you seriously reading a 1993 book (assuming 2nd edition) in 2012? Books about "C++" from before 1998 aren't even relevant.
Last edited on Aug 6, 2012 at 6:59pm
Aug 6, 2012 at 10:29pm
I still don't understand why he uses the braces to and why he didn't declare a constructor function.

Anyway, what book do you suggest I read?
Aug 6, 2012 at 11:27pm
Aggregate types (essentially, C-style arrays and C-compatible structs) are just well, aggregates of data, without behavior or OO relationships. That's the syntax used to initialize them, since they don't have constructors. You could certainly give that class a constructor if you feel that one makes sense.

As for reading, Primer 5th edition is in print now, that should be the definitive textbook once it hits the shelves. If you want something now, Accelerated C++ and Programming Principles and Practice are the way to go.
Aug 6, 2012 at 11:39pm
It is important to know the definition of an entity you are dealing with. According to the C++ Standard

1 An aggregate is an array or a class with... no private or protected non-static data members (Clause 11),..."

In ypur original example class data members are private.
Topic archived. No new replies allowed.