13

I'd like some information about best practices when comparing pointers in cases such as this one:

class Base {
};

class Derived
    : public Base {
};

Derived* d = new Derived;
Base* b = dynamic_cast<Base*>(d);

// When comparing the two pointers should I cast them
// to the same type or does it not even matter?
bool theSame = b == d;
// Or, bool theSame = dynamic_cast<Derived*>(b) == d?
Paul Manta
  • 30,618
  • 31
  • 128
  • 208

2 Answers2

7

If you want to compare arbitrary class hierarchies, the safe bet is to make them polymorphic and use dynamic_cast

class Base {
  virtual ~Base() { }
};

class Derived
    : public Base {
};

Derived* d = new Derived;
Base* b = dynamic_cast<Base*>(d);

// When comparing the two pointers should I cast them
// to the same type or does it not even matter?
bool theSame = dynamic_cast<void*>(b) == dynamic_cast<void*>(d);

Consider that sometimes you cannot use static_cast or implicit conversion from a derived to a base class:

struct A { };
struct B : A { };
struct C : A { };
struct D : B, C { };

A * a = ...;
D * d = ...;

/* static casting A to D would fail, because there are multiple A's for one D */
/* dynamic_cast<void*>(a) magically converts your a to the D pointer, no matter
 * what of the two A it points to.
 */

If A is inherited virtually, you can't static_cast to a D either.

Johannes Schaub - litb
  • 496,577
  • 130
  • 894
  • 1,212
  • 1
    Another safe bet would be to use `static_cast` to convert both of them to a common base. Provided, of course, that you know the common base. Otherwise: if one pointer is a base type of the other, the compiler will do the conversion automatically. – James Kanze Apr 14 '11 at 14:07
5

You do not require any cast in the above case, a simple Base* b = d; will work. Then you can compare the pointers like you are comparing now.

Naveen
  • 74,600
  • 47
  • 176
  • 233