Design pattern – force field initialization not by constructor in C ++

You can not force a subclass or a user of a class to perform certain actions after the constructor completes. Therefore, all initialization work MUST be performed in the constructor. There is rarely a good reason to ever have a semi-initialized object.

Typically, here the base class would assume a collection as a constructor parameter, e.g.

#include 
#include 
#include 

Class options {
protected:
std :: vector Items;
Public:
Options (std :: vector&& items): items {std :: move (items)} {}

void printItemsInConsole () {
for (auto & item: items)
std :: cout << item << & # 39;
}
};

Class MainOptions: public options {
Public:
MainOptions (): Options ({"Open game", "Open Highscores", "Exit"}) {}

};

Class SideOptions: public options {
Public:
SideOptions (): Options ({"Clear Game Data", "Uninstall", "Back to Main Menu"}) {}
};

int main () {
Main options o;
o.printItemsInConsole ();
}

Note that using the C ++ 11 list initializer for the subclass is a difficult way to deploy these items. If you do not want to provide these elements inline, you can always use a helper function to construct the vector.