0

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.

2 Answers 2

1

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.

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

Comments

1

You can do it like this in C++11

class B{
    string name;
    A array[3]; 

public:

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

Comments

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.