Jump to content
  • Advertisement
Sign in to follow this  
furiousuk

Classes Linking to each other

This topic is 4658 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

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?

Share this post


Link to post
Share on other sites
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.

Share this post


Link to post
Share on other sites
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.

Share this post


Link to post
Share on other sites
Sign in to follow this  

  • Advertisement
×

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

We are the game development community.

Whether you are an indie, hobbyist, AAA developer, or just trying to learn, GameDev.net is the place for you to learn, share, and connect with the games industry. Learn more About Us or sign up!

Sign me up!