Search code examples
c++virtualfunction-pointers

How to compare two pointers to object by their most derived type?


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; 
} 

Solution

  • 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.