Page 1 of 1

Constructor of "Game" class

Posted: November 11th, 2022, 2:48 am
by feli_lecchini
I'm kinda new to C++ and i don't understand why the parameters of the Game class constructor has a "class" keyword before the MainWindows& wnd. Any explanations on this ? I mean, i thought the Game class' constructor should be something like this:

Game(MainWindow& wnd);

but instead is:

Game(class MainWindow& wnd);

What is that "class" keyword doing ?

Re: Constructor of "Game" class

Posted: November 29th, 2022, 8:47 am
by albinopapa
In C++ there is something called forward declarations. Because C++ relies on headers ( .h files ) and including header A that includes header B which includes header A would be a never ending loop of inclusions we forward declare some classes to avoid this. The way you do this is with the 'class' keyword for classes.

So in this instance, Game.h needs to know about MainWindow, but MainWindow.h needs Game.h. To avoid circular dependencies, the MainWindow.h file include's Game.h and the MainWindow class is forward declared as a parameter to Game.

There are rules for forward declarations. You can only use forward declarations in headers that don't try "using" objects of the forward declared class.

Pass by pointer ( class Type* object ).
Pass by reference ( class Type const& object ).
And when used as a return ( Type Function() )
You may not store or pass by value a forward declared object, but you can store and pass by reference or pointer.

Re: Constructor of "Game" class

Posted: December 2nd, 2022, 11:49 am
by feli_lecchini
Ohhh, I see. Thanks