-
object interaction
I want to declare two classes, say Cat and Dog, then when they meet in my game I want them to be able to question each other.
My problem is that if you declare Dog first then it can't ask Cat any questions and its the same the other way.
Is there a way the instances can interrogate each other to find out what methods and data they have?
Is there a way to avoid this problem? Would advance declaration do it?
This must happen all the time, I'm just new.
Can anyone help?
-
well, fundamentally they way you describe the nature of the problem is such that it is recursive. if you define two instances of them beforehand, perhaps they can interact...
-
From a design point of view, you want to minimize dependencies, and especially reduce mutual dependencies. There is no reason a Dog should depend on a Cat, nor any reason a Cat should depend on a Dog.
-
Well, this is more of a C++ problem, not a game programming problem. Anyway :
I can think of a couple of ways to do this ( I have no idea if they'll work! ):
The 1st method
When defining the interface for Dog, use references of and pointers to Cat. And forward declare cat, before Dog's interface.
When implementing Dog, include the Cat interface.
The 2nd method
Make a base class that has methods for messaging and interaction. Pass Dog to Cat as an instance of the base class, pass cat to dog as an instance of the base class.
For example :
Code:
// object.h
class T_Object
{
public:
virtual void Action( int action,void *pParameters ) = 0;
public:
enum
{
ACT_MOVE, // cat and dog
ACT_ATTACK, // cat and dog
ACT_BARK, // dog only
ACT_BITE // cat and dog
};
};
// Dog.h
#include "object.h"
class T_Dog : public T_Object
{
private:
virtual void Action( int action,void *pParameters )
{
switch( action )
{
case ACT_BARK:
Bark( pParameters );
break;
case ACT_BITE:
Bite( pParameters );
break;
case ACT_MOVE:
Move( pParameters );
break;
.
.
.
}
}
void Bark( void *pParameters )
{
// Cast parameter to whatever you want
struct T_BarkParam
{
int volume,length;
};
T_BarkParam *pBarkParam = (T_BarkParam*)pParameters;
// Do whatever you want with the bark parameters and return
Snd_PlaySound( "bark.wav",pBarkParam->volume,pBarkParam->length );
}
.
.
.
};
// Cat.h
#include "object.h"
// Same as dog.h
-
do this
class Dog;
class Cat;
at the top of your code. Then later when you are implimenting Dog or Cat it will know that the other is a class.