Search code examples
c++constructorinitializer

Initialize first entries of an array of objects in class constructor initialization list


If I have class A that declares Class B and instantiates an array of it.

class A{
    class B{
        int x, y;
    };
    B arrB[10];

 public:
    A();
};

Then, my issue is that I would like to initialize the first two objects of "arrB" in Class A using initialization list:

A::A(): arrB[0](1, 2), arrB[1](3, 4) {}

But the compiler does not accept it.

Can I initialize specific objects of the array or not? If yes, how to do it?

Thanks


Solution

  • The problem is that B hides its members by default as private because it is a class. Declare B a struct, or expose int x, y as public to be able to use aggregate initialization:

    class A{
        class B{
            public:
            int x, y;
        };
        B arrB[10] = {{1,2}};
    
     public:
        A();
    };
    

    The second problem is that you're not using aggregate initialization properly.

    A::A(): arrB[0](1, 2), arrB[1](3, 4) {}
    

    Should be

    A::A(): arrB{{1, 2}, {3, 4}} {}
    

    Demo