Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Initializing map and set class member variables to empty in C++?

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?

like image 661
Marek Miettinen Avatar asked Dec 03 '10 10:12

Marek Miettinen


People also ask

Can we initialize data members in a class C?

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.

How do you initialize a class variable?

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.

Are class members zero initialized?

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.


1 Answers

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.

like image 86
CB Bailey Avatar answered Oct 26 '22 00:10

CB Bailey