Search code examples
c++pointerspolymorphismvirtualabstract

Identifying derived class from base class


Is there any way to check if two instances are the same derived class? Something like:

Base *inst1 = new A();
Base *inst2 = new B();
Base *inst3 = new A();


bool b1 =  (inst1->class== inst2->class); //<-- should evaluate to false
bool b1 =  (inst2->class== inst3->class); //<-- should evaluate to true

Obviously I could just add a virtual function to the base class and implement each derived class to return a unique value. However, I would prefer not having to implement anything specific for the derived class as I am making an API based around deriving from this base class.


Solution

  • typeid(*inst1) == typeid(*inst2)
    

    assuming that Base has at least one virtual function. Otherwise, typeid won't be able to get the right derived type.