Resantic Resantic - 1 year ago 122
C++ Question

C++ class constructor clears map

My first constructor edits a member

and then calls another constructor. At the end of the first constructor the size of the map is 2, and at the start of the second constructor it's 0. What is causing this?

Here is my header file:

// Test.h
#include <map>
#include <string>

class Test
Test(std::string name, int age);

std::map<std::string, int> myMap_;

And here is my code:

// Test.cpp
#include "test.h"

std::cout << myMap_.size() << std::endl; // Outputs 0

Test::Test(std::string name, int age)
myMap_.insert(name, age);
myMap_.insert("test", 6);

std::cout << myMap_.size() << std::endl; // Outputs 2

And here is my main function:

#include "test.h"

int main()
Test t("yo", 4);
return 0;

Answer Source

The second constructor inserts 2 elements. So the size is 2.

The first constructor inserts no elements. So the size is 0.

I guess maybe you expect Test(); inside the second constructor to "call the other constructor" for the same object. However this does not happen. Constructors are different to regular functions.

The code Test(); actually means to create a temporary object of type Test, which is initialized by calling the default constructor. Then that object is destroyed immediately, since it was temporary.

Constructors have no name, as far as name lookup is concerned, it's not possible to call them like regular functions. Instead they are invoked when you give the syntax to create an object.

If you want to have some common code that is shared by multiple constructors; you could either put that code in a function that is called by the multiple constructors, or use the delegating constructors feature. In the latter case, the delegation must happen before any statements inside the constructor body are executed.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download