Paul Manta
Paul Manta

Reputation: 31577

C++: Comparing pointers of base and derived classes

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?

Upvotes: 14

Views: 5327

Answers (2)

Johannes Schaub - litb
Johannes Schaub - litb

Reputation: 507035

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.

Upvotes: 7

Naveen
Naveen

Reputation: 73443

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.

Upvotes: 5

Related Questions