Reputation: 23
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 :)
Upvotes: 1
Views: 1510
Reputation: 1
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.
Upvotes: 7
Reputation: 409136
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);
}
Upvotes: 3