I’m currently trying to make a RPG game and I’m running into some trouble. This is the layout I have so far.
Classes:
- Actor – Base class for anything that ‘exists’ such as units, projectiles, etc.
- Unit – Inherits Actor, basis for all units.
- Game – It will only have a single instance, and it’ll contains pointers to all objects in the game. I plan to make it call a virtual function gameTick on all actors every 0.1 seconds.
The problem I’m having is that I’d like all Actors to have a pointer to the Game instance. If I wanted to have a spell that does 500 radius area damage, I’d like Game to find and return all Unit pointers within that range.
My problem is if I include Game in Actor’s header file my program won’t compile. How can I have my actors have access to Game? Or am I going about this the wrong way?
Thanks in advance.
// START main.cpp
#include <iostream>
#include "game.h"
int main()
{
std::cout << "All done\n";
return 0;
}
// END main.cpp
// START actor.h
#ifndef __ACTOR_H_
#define __ACTOR_H_
#include <iostream>
//#include "game.h" Causes many errors if uncommented
class Actor
{
public:
Actor();
std::string name_;
};
#endif
// END actor.h
// START actor.cpp
#include "actor.h"
Actor::Actor()
{
name_ = "Actor class";
}
// END actor.cpp
// START unit.h
#ifndef __UNIT_H_
#define __UNIT_H_
#include "actor.h"
class Unit : public Actor
{
public:
Unit();
};
#endif
// END unit.h
// START unit.cpp
#include "unit.h"
Unit::Unit()
{
name_ = "Unit class";
}
// END unit.cpp
// START game.h
#ifndef __GAME_H_
#define __GAME_H_
#include <vector>
#include "unit.h"
class Game
{
public:
std::vector< Actor * > actors_;
std::vector< Unit * > units_;
};
#endif
// END game.h
Instead of doing:
you can simply forward declare the two classes:
Since you’re only using pointers, the compiler just needs to know that the type is a class, it doesn’t need to know anything else. Now in the cpp file, you’d need to do the
#includes