If I own a C++ base class but don't own or even know about derived classes, can I tell if a given object is an instance of a derived class?

170 views Asked by At

I can't use dynamic_cast because I don't know the names of the derived classes. Similarly for std::is_base_of.

1

There are 1 answers

0
Brian Bi On

Your question is basically how to check whether the dynamic type of the object that you have (by pointer or reference to Base) is actually Base. This is a job for typeid:

struct Base { /* ... */ };

bool is_actually_base(Base& b) { return typeid(b) == typeid(Base); }

If this test returns false, the object must be of a derived class type (or you messed up somewhere and your program has undefined behaviour).

Note that this works only if Base contains at least one virtual function (possibly inherited). If that isn't the case, then there is no way to check.