How do I find out the type of a variable when inheritance is involved?
I’m having a little situation, I’ll describe it in pseudocode:
class A
{
public:
A();
virtual ~A();
protected:
//some members
};
class B : public A
{
public:
B();
virtual ~B();
protected:
//some members
};
///////////////////////
int main()
{
A* pA = new B();
std::cout<<"type of pA: "<< ???;
}
How can I find out the type of pA? the result should be B. Also, what should I do if I want the result to be A?
Thanks.
EDIT:
I’ll let you be the judge of whether it is bad design or not. If you think it is, then please tell me a better alternative.
Code:
class MyContactReport : public NxUserContactReport
{
void OnContactNotify(NxContactPair& pair, NxU32 events)
{
if (pair.actors[0]->userData == NULL || pair.actors[1]->userData == NULL) return;
LevelElement* otherObject = (LevelElement*)pair.actors[1]->userData;
LevelElement* triggerObject = (LevelElement*)pair.actors[0]->userData;
switch(events)
{
case NX_NOTIFY_ON_START_TOUCH:
triggerObject->OnContactStartTouch(otherObject);
break;
case NX_NOTIFY_ON_END_TOUCH :
triggerObject->OnContactEndTouch(otherObject);
break;
case NX_NOTIFY_ON_TOUCH:
triggerObject->OnContactTouch(otherObject);
break;
}
}
} *myReport;
pair.actors[1]->userData gives me access to the userData from an actor, an actor is something of the PhysX framework, that determines collisions and physics etc. The userdata is of type void*.
This is also the only way to find out object the actor actually belongs to.
Then there’s class LevelElement, an abstract class where every object in my level inherits from (level as in a game-level)
LevelElement has protected virtual methods: OnContactTouch(LevelElement* pOtherElement) etc…
In those methods, I need to find out what type of LevelElement it is, to take certain specific measures.
Is this bad design? If yes, please help!
Use the typeid operator, as described for example here.
Basically:
[…]
Results, with g++ 4.4.5:
I.e. there is some mangling involved at least using gcc. Check out this question for how to deal with this.
EDIT: As for your design question, instead of checking what type the otherObject is, a better solution is to just tell this object what to do. Assuming you want to code the onContactTouch for a hypothetical Bullet object; instead of
do this:
This is sometimes called the tell, don’t ask principle.