0

I have a Visual Studio 2008 C++03 project where I would like to verify if an object is of a certain type.

For example:

int main()
{
    struct A { virtual ~A() { }; };
    struct B : public A { };
    struct C : public A { };

    A* b = new B();
    A* c = new C();

    assert( typeof( b ) == typeof( B ) );
    assert( typeof( b ) != typeof( C ) );

    assert( typeof( c ) == typeof( C ) );
    assert( typeof( c ) != typeof( B ) );

    assert( typeof( b ) != typeof( c ) );
    return 0;
}

Is there a way to do this in C++03? How?

PaulH
  • 7,759
  • 8
  • 66
  • 143

2 Answers2

1

You can use dynamic_cast to attempt to cast it to a base/derived type. If it does not return NULL then it is a base class or derived from that type (depending if you cast up the hierarchy or down)

Casey
  • 10,297
  • 11
  • 59
  • 88
0

You can use typeinfo for getting the type of an object.
Or you could use dynamic_cast to check if an pointer points to object of appropriate type.

Community
  • 1
  • 1
Alok Save
  • 202,538
  • 53
  • 430
  • 533