Identification of a derived class from a base class

Is there a way to check if two instances are the same derived class? Sort of:

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 to do anything specific for the derived class, as I am creating an API based on this base class.

+4
source share
2 answers
 typeid(*inst1) == typeid(*inst2) 

assuming Base has at least one virtual function. Otherwise, typeid will not be able to get the correct derived type.

+8
source

I do not know the method that returns the class from which the instance is derived. However, dynamic_cast can be used to check if an instance is compatible with a particular class.

A & inst_ans = dynamic_cast (inst2); throws an exception

where as & amp; inst_ans = dynamic_cast (inst1); will execute correctly

http://en.wikipedia.org/wiki/Dynamic_cast

0
source

Source: https://habr.com/ru/post/1437278/


All Articles