Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ init member variables with multiple constructors

Tags:

c++

Usually a constructor should look like this:

//ctor1
SmallSim::SmallSim()
:mSimInit(false)
,mServersCreated(false)
,mTotalCPUTime(0)
{
    ...
}

What happens if I have multiple constructors?

It looks to me that If I call the first constructor from my second, the member vars in the first do not get initialized.

//ctor2
SmallSim::SmallSim(bool ImmediateExecution, bool Report)
{
    SmallSim();

    ...
}

So do I need to repeat :mSimInit(false) ,mServersCreated(false) ,mTotalCPUTime(0) on every constructor I have?

As far as I know using an InitClassVars() is not the best way to go...

//ctor1
SmallSim::SmallSim()
{
    InitClassVars();

    ...
}

//ctor2
SmallSim::SmallSim(bool ImmediateExecution, bool Report)
{
    InitClassVars();

    ...
}

//Common function for init of member vars for multiple constructors
void SmallSim::InitClassVars(void)
{
    mSimInit = false;
    mServersCreated = false;
    mTotalCPUTime = 0;
}

Is there a correct way to Init the member vars with out repeating the init on every constructor?

like image 502
DieSlower Avatar asked Dec 01 '22 22:12

DieSlower


2 Answers

If you do this:

SmallSim::SmallSim(bool ImmediateExecution, bool Report)
{
    SmallSim(); // 1

    ...
}

The line marked with 1 creates a new SmallSim temporary object which is readily destroyed since it is not used. It has no effect whatsoever on the object currently being initialized. To call another constructor on the same object you do it like this:

SmallSim::SmallSim(bool ImmediateExecution, bool Report)
: SmallSim() {
    ...
}

(This is a C++11 feature.)

like image 125
R. Martinho Fernandes Avatar answered Dec 19 '22 17:12

R. Martinho Fernandes


There are two options in C++03:

  • Use an init function which you call from every ctor
  • Provide an initializer list for all ctors

In C++11 you can use delegating ctors so that you can call one ctor from all others.

like image 27
dirkgently Avatar answered Dec 19 '22 17:12

dirkgently