I have a C++ class with two member variables
std::map<int, Node*> a;
and
std::set<Node*> b;
A style checker used at my University requires all member variables to be initialized in the constructor of the class. How can these member variables a
and b
be initialized to empty in the constructor of the class they are in?
In C++11, the language has been extended to allow specifying an initializer in the declaration, but this is just a shorthand—the actual initialization still takes place at the top of the constructor. Initialization of data members will also still occur in order of declaration.
To initialize a class member variable, put the initialization code in a static initialization block, as the following section shows. To initialize an instance member variable, put the initialization code in a constructor.
zero-initialization – Applied to static and thread-local variables before any other initialization. If T is scalar (arithmetic, pointer, enum), it is initialized from 0 ; if it's a class type, all base classes and data members are zero-initialized; if it's an array, each element is zero-initialized.
As both std::set
and std::map
have "user"-declared default constructors they will be initialized implicitly however you construct your class. You don't have to do anything special to conform with the "style" guide.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With