2

I have a class that creates instances of other classes, and when I call them, compiler gives me warning about order of the instances. Why does it matter? It does same job, regardless of the order.

E.g. I have this in my core class header file (core class handles game loop):

HUD hud;
World myWorld;

Like this they do all they need to. But compiler gives a warning:

'Core::myWorld' will be initialized after [-Wreorder]|

Then if I put myWorld instance above the hud instance, it doesn't give me warning anymore. I was just wondering, how on earth does it matter which order they are in?

Hengad
  • 23
  • 4

2 Answers2

4

Warning is since, in constructor initializer-list you initialize World before HUD, but actually members will be initialized in order they are declared in class.

Just litle example, where it can be worse:

class B
{
public:
   B(int i) : value(i) {}
private:
   int value;
};

class A
{
public:
   A() : value(10), b(value)
   {
   }
private:
   B b;
   int value;
};

Here b will be initialized before value and so, something will be sended to b constructor, but not 10 as programmer want.

ForEveR
  • 55,233
  • 2
  • 119
  • 133
0

With

struct C
{
    C() : p(std::make_unique<int>(42)), j(*p) {} // initialization doesn't use this order.

    // but the order here:
    int j;
    std::unique_ptr<int> p;
};

you will dereference nullptr as j is initialized before p.

Jarod42
  • 203,559
  • 14
  • 181
  • 302