I have a class Derived
that inherits directly from two base classes, Base1
and Base2
. I'd like to know if it's safe, in general, to compare pointers to the base classes to determine if they are the same Derived
object:
Base1* p1;
Base2* p2;
/*
* Stuff happens here. p1 and p2 now point to valid objects of either their
* base type or Derived
*/
//assert(p1 == p2); //This is illegal
assert(p1 == static_cast<Base1*>(p2)); //Is this ok?
assert(static_cast<Derived*>(p1) == static_cast<Derived*>(p2)); //How about this?
The pointers are guaranteed to be valid, but not necessarily to point to a Derived
object. My guess is that this is probably fine, but I wanted to know if it was ok from a technical C++ perspective. I actually never do any operations on the pointers, I just want to know if they point to the same object.
EDIT: It seems to be safe if I can guarantee that p1
and p2
point to Derrived
objects. I basically want to know if it is safe if they don't- if one or both point to a base object, will the comparison necessarily fail? Again, I can guarantee the pointers are valid (i.e., p1
would never point at a Base2
object or vice versa)