In my game the player will be able to go through doors which take them to different planets. My door class contains a pointer to a planet, but my problem is that when detecting collisions between the player and the doors in the world class, since I have stored pointers to the base class, CEntity, in the world class, I cannot access the unique functionality of the door class and gain access to the pointer to the planet that the door leads to.
I know I could put the pointer to the planet in the base class but this seems sloppy could anyone suggest how to better design this.
A lot of this depends on your actual design structure. Does every CEntity have an activate() function? You could have the CEntities list their activities to the caller and then the caller can call their activate() function with one of the returned activity codes.
#include <string>
#include <vector>
typedef std::pair<int, std::string> activity;
typedef std::vector<activity> activity_list;
class Place
{
public:
std::string get_name();
};
class User
{
public:
void set_location(Place& place);
void tell(const std::string& message);
};
class CEntity
{
public:
virtual ~CEntity(){}
virtual activity_list get_activity_list() = 0;
virtualvoid perform_activity(int code, User& user) = 0;
};
class CDoor
: public CEntity
{
private:
Place destination;
enum
{
LOCK
, UNLOCK
, OPEN
, ENTER
};
public:
virtual activity_list get_activity_list()
{
activity_list list;
list.push_back(std::make_pair(int(LOCK), "Lock the door."));
list.push_back(std::make_pair(int(UNLOCK), "Unock the door."));
list.push_back(std::make_pair(int(OPEN), "Open the door."));
list.push_back(std::make_pair(int(ENTER), "Enter through the door."));
return list;
}
virtualvoid perform_activity(int code, User& user)
{
switch(code)
{
case LOCK:
// Stuff
break;
case UNLOCK:
// Stuff
break;
case OPEN:
// Stuff
break;
case ENTER:
user.set_location(destination);
std::string message = std::string("You are transported to ") + destination.get_name();
user.tell(message);
break;
default:
user.tell("Sorry, I can't do that.");
}
}
};
Much of that can be generalised and the activity codes and descriptions can be stord on file and read. Then one type of object can function as many different things. So a Door class can be a portal, gate, trapdoor, catapult... etc...
thanks bazzy dynamic_cast does the job. In this case I am certain that at this point in the code the object pointed to will always be a door, so would static_cast be more efficient? I know very little about casts but dynamic_cast checks that the cast was successful, yes? Is there any advantage that one cast would have over the other in this case?
No, for this is better dynamic_cast, so you can be sure that the returned pointer is pointing to a valid object or it will be NULL
static_cast allows casting to an incomplete object of the derived class