Classes Linking to each other

Started by
2 comments, last by furiousuk 18 years, 3 months ago
In my project I want to allow the Map object to contain a pointer to the Player object so that when they tread on Map objects (such as teleporters or spinners) the Map moves the Player to the destination location and direction. My problem is that I also need to have the Player contain a pointer to the Map object so that it can have a knowledge of its surroundings with which to perform AI calculations (it is needed for more than just navigation). However, my Map header file contains an #include to my Player header and my Player header contains an #include to my Map header. Both header files contain a #pragma once command to combat multiple declaration problems and they won't link to each other meaning that while one class has knowledge of the other, the other doesnt. I've tried removing the #pragma once command command and using #ifndef and #define commands to declare the classes, again ending in failure. I'm using MSVC++ 6.0 How do two different classes link to one another?
Advertisement
You can use forward declarations when you declare variables to a pointer to a type without needing the full details of the type. ex:
class Player;class Map {  public:    // stuff  private:    Player * player_;};

For more details see this article.
By making a forward declaration:

map.h:
class player;class map{  player *p;  // ...};

player.h:
#include "map.h"class player{  map *m;  // ...};

map.cpp:
#include "map.h"#include "player.h"// implementation


Note that there is very little you can do with a class that is only forward declared. Because the compiler knows nothing about it except the name, you cannot create objects of that type, nor can you actually use such an object in any way even if you have a pointer or a reference to the object.
Cheers, think that's help me sort out the problem.
Article was useful too.

Thanks

This topic is closed to new replies.

Advertisement