views:

222

answers:

2

I have a following class hierarchy:

class Base{
....
virtual bool equal(Base *);
}

class Derived1: public Base{
....
virtual bool equal(Base *);
}
class Derived2: public Derived1{
}
class Derived3: public Derived1{
}
class Derived4: public Base{
}

How I should write Base::equal(Base *) function such that compares Derived4 and similar classed? They don't have data fields, so check only that actual objects are of same derived class.

And how to write Derived1::equal(Base) - the Derived2 and Derived3 are similar they don't have any data field and the should be compared by data fields in Derived1 and check that objects are from the same derived class?

Update: I want this because I don't want to write identical functions to each Derived class such as:

bool Derived::equal(Base *b){ 
  Derived *d = dynamic_cast<Derived*>(b); 
  return d; 
}
+2  A: 

I think you can use typeid operator here. You can do something like:

typeid(*pointerBase) == typeid(*this);

But why do you want to do something like this? It looks very suspicious, I suggest to take a relook at the design.

Naveen
name return char*. Comparing pointer isn't right. use typeid(*this)==typeid(*pointerBase) directly
aJ
+2  A: 

The generic technique that can be used for polymorphic inter-type comparisons is called "double dipatch" (see Double Dispatch). It can be applied to your specific problem, in which case you'll end up with a bunch of overloaded functions with almost empty bodies, just returning either 'false' or 'true'.

Of course, if you just want to compare dynamic types and nothing else, you can just do it through run-time type information (i.e. use 'typeid').

AndreyT
Sidenote: There's also Multiple Dispatch (http://en.wikipedia.org/wiki/Multiple%5Fdispatch) to implement Multi Methods.
sbi