My question is related to RTTI in C++ where I'm trying to check if an object belongs to the type hierarchy of another object. The BelongsTo() method checks this. I tried using typeid, but it throws an error and I'm not sure about any other way how I can find the target type to convert to at runtime.
#include <iostream>
#include <typeinfo>
class X
{
public:
// Checks if the input type belongs to the type heirarchy of input object type
bool BelongsTo(X* p_a)
{
// I'm trying to check if the current (this) type belongs to the same type
// hierarchy as the input type
return dynamic_cast<typeid(*p_a)*>(this) != NULL; // error C2059: syntax error 'typeid'
}
};
class A : public X
{
};
class B : public A
{
};
class C : public A
{
};
int main()
{
X* a = new A();
X* b = new B();
X* c = new C();
bool test1 = b->BelongsTo(a); // should return true
bool test2 = b->BelongsTo(c); // should return false
bool test3 = c->BelongsTo(a); // should return true
}
Making the method virtual and letting derived classes do it seems like a bad idea as I have a lot of classes in the same type hierarchy. Or does anybody know of any other/better way to the do the same thing? Please suggest.
Update: b.BelongsTo(a) should detect if the input object type (a) is an ancestor of the current object (b) in the type hierarchy.