PaulH
PaulH

Reputation: 7873

Verify base object is of a particular derived type

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?

Upvotes: 0

Views: 122

Answers (2)

Alok Save
Alok Save

Reputation: 206646

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.

Upvotes: 0

Casey
Casey

Reputation: 10966

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)

Upvotes: 1

Related Questions