When using const members in your class you have to construct them in a initializer list. But in which order should you construct them ? I created a example where the order actually matters — we need Cylinders first before we can construct a Car’s engine. But the following code holds a nasty bug. Can you spot it ?

struct Engine{
std::vector<std::string> cylinders;
};
class Car{
public:
const Engine mEngine;
const std::vector<std::string> mCylinders;
Car(std::vector<std::string> cylinders):
mCylinders(cylinders),mEngine(mCylinders){}
};

Here is an basic main() function that constructs a Car and then prints all cylinders in the car’s engine:

int main()
{…

Constantin Marcel

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store