Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there an idiomatic approach in C++ for comparing polymorphic types for object equivalence?

I have Base* pointers to two instances of a polymorphic type and I need to determine if the referenced objects are equivalent.

My current approach is to first use RTTI to check for type equality. If the types are equal, I then call a virtual is_equivalent function.

Is there a more idiomatic approach?

like image 552
RandomBits Avatar asked Feb 15 '12 04:02

RandomBits


1 Answers

For most of the derived classes, equivalent simply means that the member variables all the same value

In C++ this is called 'equality' and is usually implemented using operator==(). In C++ you can override the meaning of operators, it is possible to write:

MyType A;
MyType B;
if (A == B) {
    // do stuff
}

And have == call a custom function you define.

I think you want to differentiate equality from identity which would mean the same object (i.e. same address).

You can implement it as member function or free function (from wikipedia):

bool T::operator ==(const T& b) const;
bool operator ==(const T& a, const T& b);

In your case you want to implement operator== for the base class, and then perform what you are doing.

More concretely it would look like this:

class MyBase
{
    virtual ~MyBase(); // reminder on virtual destructor for RTTI
    // ...
private:
    virtual bool is_equal(const MyBase& other);

    friend bool operator ==(const MyBase& a, const MyBase& b); 

    // ...    
};

bool operator ==(const MyBase& a, const MyBase& b)
{
    // RTTI check
    if (typeid(a) != typeid(b))
        return false;
    // Invoke is_equal on derived types
    return a.is_equal(b);
}


class D1 : MyBase
{
    virtual bool is_equal(const Base& other)
    {
        const D1& other_derived = dynamic_cast<const D1&>(other);
        // Now compare *this to other_derived
    }
};

class D2 : MyBase;
{ };


D1 d1; D2 d2;
bool equal = d1 == d2; // will call your operator and return false since
                       // RTTI will say the types are different
like image 118
J.N. Avatar answered Oct 22 '22 07:10

J.N.