Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if two (smart) pointers point to the same derived class

Tags:

c++

c++11

Let's say I have a base abstract class B and a hundred classes which derive from it D1 ... D100. I also have two (smart) pointers unique_ptr<B> p1, p2; which point to two different instances of types Di and Dj. I want to know whether the objects they're pointing to have the same type (i.e. whether i equals j). Is there a simple way to do that?

like image 395
Valentin Avatar asked Sep 19 '25 20:09

Valentin


1 Answers

You can use a RTTI typeid, but generally, it is a bad design to must have to use dynamic_cast because it may violate the liskov substitution principle

std::unique_ptr<B> p1, p2;
if(typeid(*p1) == typeid(*p2)) // correction by Justin

Or something like that using name or hash_code

like image 157
Antoine Morrier Avatar answered Sep 22 '25 09:09

Antoine Morrier