-1

I have three class. First one is the 'Game', which is dependent to the other two. My second class is 'Window', which is a dependence for the third class 'VKBase'. Those last two classes have no parameters in their constructor functions. Game contains the others as object members, and Window have to get initialised before VKBase.

class Game
{
    Boolean bit = true;

    Window window;

    VKBase VkBase;

public:

    Game();
   ~Game();

    void _Set();

    void Loop();

    void Exit();
};

Because that these two class not have parameters in their constructor functions, i can't initialise them in the constructor function of the Game. So they will get initialised whenever i create an object from the class Game.

But the question is, since initialisation order is important, which one will get initialised first? The window or the VkBase?

  • 2
    Member variables are initialised in declaration order. See __Initialization order__ point (3): https://en.cppreference.com/w/cpp/language/initializer_list – Richard Critten Aug 19 '18 at 18:29

2 Answers2

1

Initialization order is always left-to-right: first class bases, left-to-right, then member variables in declaration order. So the first one to be initialized in your class is bit, and then follows window.

bipll
  • 11,747
  • 1
  • 18
  • 32
0

In which order object class members [...] are initialized?

In the order in which they were declared. In your example, bit is initialized first, window second, VkBase third. Whether these data members have a default constructor or one depending on parameters doesn't matter here.

Because that these two class not have parameters in their constructor functions, i can't initialise them in the constructor function of the Game

You kind got that wrong, you do in fact initialize the instances by calling the default constructor. Note that for any class that has a default constructor,

ClassWithDefaultCtor instance;

does call this default constructor when this variable is instantiated (might be when an enclosing class is constructed, if the above declaration is a class data member). This syntax is called default initialization, and this is exactly what happens in your class. Note that you can change the above to

ClassWithDefaultCtor instance{};

which might make it clearer that the object is properly initialized.

lubgr
  • 37,368
  • 3
  • 66
  • 117