Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 533
bofjas Avatar asked Feb 18 '23 23:02

bofjas


1 Answers

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.

like image 98
Pete Becker Avatar answered Feb 27 '23 21:02

Pete Becker