1

I have this class:

class Taxi {
   Wheel myWheel[4];
public:
   Taxi();
};

and Wheel is another class contain:

class Wheel{
   int radius,
       tickness;
public:
   Wheel(int,int);
};

now, what i want to do is to initialize "myWheel[4]" in initialization list of Taxi constructor, like this:

Taxi::Taxi () :Wheel[0](5,5), Wheel[1](3,3), Wheel[2](5,5), Wheel[3](3,3) {
   cout << "Ctor of Taxi" << endl;
}

but it doesn't work and i really need some HELP, thanks :)

2 Answers 2

7

Your initialization list should look like

Taxi::Taxi () : myWheel { Wheel(5,5), Wheel(3,3), Wheel(5,5), Wheel(3,3)} {
   cout << "Ctor of Taxi" << endl;
}

See a LIVE DEMO

If you don't have a compiler compliant with the current c++ standard (c++11), there's no way to do this in the member initializer list. You have to initialize the array elements inside the constructor's body:

Taxi::Taxi () {
   cout << "Ctor of Taxi" << endl;
   myWheel[0] = Wheel(5,5);
   myWheel[1] = Wheel(3,3);
   myWheel[2] = Wheel(5,5); 
   myWheel[3] = Wheel(3,3);
}

Also note you should make Wheel a nice class then.

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

8 Comments

it doesn't work :/ errors: -only '()' is allowed as initializer for array member "AutoTaxi::_taxiWheel" -expected a declaration -expected a ';' -'AutoTaxi::AutoTaxi::_taxiWheel' : cannot specify explicit initializer for arrays
@Naama Well, the linked demo works. Are you sure to have replicated the code correctly? I had to fix some other errors until it worked. Also note the order of declaration for Wheel and Taxi. What's your compiler version language standard flags actually?
@Naama, this requires C++11
#πάντα ῥεῖ Sorry for the ignorance but I don't know how to check compiler version. I know I'm using visual studio pro 2013 version 12.0.21
Check this Q&A then please: Workaround for error C2536: cannot specify explicit initializer for arrays in Visual Studio 2013. It looks like VS2013 (supporting c++11 by default) is broken about this.
|
3

You can only initialize arrays if you have a C++11 capable compiler, and then you can do

Taxi::Taxi () :myWheel{{5,5}, {3,3}, {5,5}, {3,3}} { ... }

If you don't have a C++11 capable compiler, then you have to initialize the array manually:

Taxi::Taxi()
{
    myWheel[0] = Wheel(5, 5);
    myWheel[1] = Wheel(3, 3);
    myWheel[2] = Wheel(5, 5);
    myWheel[3] = Wheel(3, 3);
}

3 Comments

doesn't work as well.. error: cannot specify explicit initializer for arrays
I don't think the second variant is legal C++.
Everyone are correct, it was not valid in pre-C++11. Updated my answer

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.