user2007843 user2007843 - 9 months ago 32
C++ Question

Set initial values of member variables when constructor is run

I have a class that is partially shown below in a header file

class Data {

bool network_decision_;
bool network_finished_;

How can I set the initial values of those boolean member variables when the constructor is run?


You have 3 options:

In-class initialization

class Data {

    bool network_decision_ = true;
    bool network_finished_ = false;

Using the constructors initialization list

Data::Data() : network_decision_(true), network_finished_(false) {}

Use the constructor body

Data::Data() { network_decision_ = true; network_finished_ = false; }

Each method will overwrite the value set by the previous (in the order listed) which can sometimes come in handy. Also note that the last option is the least prefered since you'll actually be default consteucting the objects first when the initialization list runs and then overwrite the value - more expensive in some cases, so use one of the first two methods when you can.