(using C++ in Visual Studio)
I have the following default constructor used to create a spaceship object:
Ship() // default constructor
{
name = "[ship unnamed]";
length = 1000;
width = 500;
power = 100;
vector<int> temp = { 100, 100 }; // { current health, maximum health}
bridge = temp;
sensor_arrays.push_back(temp); // 2 sensor arrays
sensor_arrays.push_back(temp);
for (int i = 0; i < 12; i++) // create 12 each
{
lasers.push_back(temp);
heavy_lasers.push_back(temp);
strike_fighters.push_back(temp);
strike_bombers.push_back(temp);
}
}
Then I have the following parameterized constructor used to create a ship given a name:
Ship(string custom_name)
{
name = custom_name;
length = 1000;
width = 500;
power = 100;
vector<int> temp = { 100, 100 }; // { current health, maximum health}
bridge = temp;
sensor_arrays.push_back(temp); // 2 sensor arrays
sensor_arrays.push_back(temp);
for (int i = 0; i < 12; i++) // create 12 each
{
lasers.push_back(temp);
heavy_lasers.push_back(temp);
strike_fighters.push_back(temp);
strike_bombers.push_back(temp);
}
}
Only one single line changed, so this appears to violate DRY.
I could just use the default constructor then manually change what I need, but I'd like to have one or more parameterized constructors without repeating the same lines of code. Is there some way to do this?
Thanks to @Chris' answer, I implemented an initializer list as described here.
Solution: (original code in question)
Ship(string custom_name) : Ship()
{
name = custom_name;
/*length = 1000;
width = 500;
power = 100;
vector<int> temp = { 100, 100 };
bridge = temp;
sensor_arrays.push_back(temp); // 2 sensor arrays
sensor_arrays.push_back(temp);
for (int i = 0; i < 12; i++) // create 12 each
{
lasers.push_back(temp);
heavy_lasers.push_back(temp);
strike_fighters.push_back(temp);
strike_bombers.push_back(temp);
}*/
}