Search code examples
c++list-initialization

C++11: how List-initialization assign values in a user defined object?


I have a class Library, and it includes a member object shelf1 from another class Shelf.

The Class Shelf have several variables, say:

class Shelf {
int height;
int width;
int materialType;
String shelfName;
}

Now in Library, I want to initialize the member object shelf1 in the Library declaration:

Shelf shelf1{100, 200};
Shelf shelf2{100, "fiction"};

Can they work, and how List-initialization works for the order of variables?

[Update] Those code are for explanation of my question (I do have a similar code in my real world. But it is too complicated to put here. So I simplify my question).


Solution

  • If your class is an aggregate, then the variables are initialized according to the order of declaration in your class. For your class to be an aggregate (and be able to use such direct list initialization), one of the requirements is that all members must be public (thanks to @Praetorian for catching this), otherwise your class is not an aggregate and the code won't compile. So, assuming the members are public,

    Shelf shelf1{100, 200}; 
    

    initializes height with 100 and width with 200.

    Shelf shelf2{100, "fiction"};
    

    is a compile-time error, as the second member width is not a C-string.

    More details here.