Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Chris Miller on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Mutual Inclusion

Status
Not open for further replies.

fatlardo

Programmer
May 7, 2007
41
GB
I realise this seems a stupid question but I have googled this to death with no results so here goes:

I have two files, game.h and player.h. Each contains a reference to the other.

I started by simply putting an include to the other each file. This resulted in an infinite loop when I compiled the program, fair enough really!

So I tried the following, which I found in a c++ forum.

player.h
[tt]
#ifndef PLAYER_H
#define PLAYER_H

class Player() {
...
thisIsAFunction( Game&; );
...
}

#endif
[/tt]

game.h
[tt]
#ifndef GAME_H
#define GAME_H

class Game() {
...
}

#endif
[/tt]

The problem I have now is that the compiler reports an error on the [tt]thisIsAFunction( Game&; );[/tt] line. 'Game' has not been declared.

I should mention that the main.cpp file includes game.h, the game class (an instance of which is created by the main() function) has a member of type Player and the method in the Player class requires a Game object to be passed to it (otherwise I wont be able to draw to the screen!!)

Does anyone know any way around my problem? If I cant do this mutual inclusion thing it could make my code almost unmanageably longer!!!

I am using the gcc complier (i think, not sure how to check!) and using Code::Blocks IDE.

HELP!!!!!!!
 
Try
Code:
#ifndef PLAYER_H
#define PLAYER_H

[red]class Game;[/red]
class Player() {
...
thisIsAFunction( Game&; );
...
}

#endif
It's a forward reference, which tells the compiler that Game will be properly declared later. But for now, it only knows that the class exists. So you can't create instances of a Game, but you can point to a Game.



--
If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top