dranec
dranec

Reputation: 57

The proper order of Initialization of variables in constructor

So here is my problem, im trying to learn some code and im just playing with changing and exploring some new ways to write it, but I realized that If the declaration with the {} is not the last variable it doesnt work, (if i change the places of m_belowScene and m_overscene it works tho).

My modification:

 SceneManager::SceneManager()
    : m_scene(std::make_shared<PolyGraphicNode>()),
      m_cplSign(std::make_shared<CPLSymbol>(0.05, 0.2, 0.5)),
      m_belowScene(std::make_shared<PolyGraphicNode>()){ 
      std::shared_ptr<CPLSymbol> symbol = std::make_shared<CPLSymbol>(0.01, 0.04, 0.1, CPL_NODE);
      m_belowScene->append(symbol);
      }
      m_overScene(std::make_shared<PolyGraphicNode>());

the proper way is this

SceneManager::SceneManager()
: m_scene(std::make_shared<PolyGraphicNode>()),
  m_cplSign(std::make_shared<CPLSymbol>(0.05, 0.2, 0.5)),

  m_overScene(std::make_shared<PolyGraphicNode>()),
  m_belowScene(std::make_shared<PolyGraphicNode>()){ 
  std::shared_ptr<CPLSymbol> symbol = std::make_shared<CPLSymbol>(0.01, 0.04, 0.1, CPL_NODE);
  m_belowScene->append(symbol);
  }

Upvotes: 0

Views: 93

Answers (1)

Martin Nyolt
Martin Nyolt

Reputation: 4670

You have to distinguish between the initializer list and the body of the constructor. As tobi303 pointed out, these to cannot be mixed.

The syntax for writing a constructor is

Class::Class(<parameters>) : <initializer list> { <body> }

The <body> starts with '{'.

In an initializer list, variables are assigned values in the form variable(value)

Consider the class

class foo {
    int x;
    int y;
    int z;

    foo(int value_x, int value_y);
};

The constructor might be defined like this:

foo::foo(int value_x, int value_y) :
    x(value_x),
    y(value_y), 
    z(1)
{
}

If you want to add another variable v, and initialize it with some value, you have to put it in the initializer list like this (note the brace):

foo::foo(int value_x, int value_y) :
    x(value_x),
    y(value_y), 
    z(1),
    v(42)
{
}

Within the body, more complex operations can be used. Thus, your example shows assignment statements of the form variable = value. However, assignment statements are only allowed in the body, and not the initializer list. Similarly, initializations of the form variable(value) are not allowed in the body.

Thus, you have to watch out which form you use at which place.

See also the following question on the difference between these forms of variable initializations:

Upvotes: 4

Related Questions