Miguel Ruivo Miguel Ruivo - 1 month ago 12
C++ Question

Quick about C++ array class constructor

I'm trying to (force) initialize an array of 3 class elements in another class (I know I could use a vector and initializer list or so but I want to know if there's any possibility this way) and let's say I've this code for ex:

class A{
// CODE HERE, doesn't really matter
}


and then

class B{

string name;
A array[3]; <-- here's the point. I want array of 3 members of class A

public:

B(string name_, A a, A b, A c) : name(name_), array[0](a), array[1](b), array[2](c){} // Here's the problem. I can't initialize this way, it always give me some sort of error and array isn't recognized as a class variable (no color in the compiler like 'name' for ex shows and it should be).

}


if for some reason I don't initialize in the prototype and just do it inside the function like this->array[0] = a and so on, it works. But I'd like to know a way to do it inline like I displayed above.

Answer

After fixing the simply typos from your example you can use a brace initializer list for your array like this:

class A{
 // CODE HERE, doesn't really matter
};


class B{

string name;
A array[3]; // <-- here's the point. I want array of 3 members of class A

public:

B(string name_, A a, A b, A c) : name(name_), array{a,b,c} {} 
                                                // ^^^^^^^

 };

See Live Demo

Dereferencing by index isn't possible at this point.

Comments