3
votes

There is a Base class and a Derive class. Derive public inherit Base. The base class has implemented a friend function bool operator==(const Base& lhs,const Base& rhs) const; I am implementing the Derive class, which also need to implement bool operator==(const Derive& lhs, const Derive& rhs) const; Now my problem is that I do not know how to call the parents's operator== function in my operator== function. The operator== for Base class dose not belong to base, so i cannot simply use Base::operator==. Thank you.

1
Your question might be a lot clearer if you post some (pseudo)code, rather than trying to describe your code. - Oliver Charlesworth
Also, if you have a free operator==(), then it isn't meaningful to say that "the base class has implemented it". - Oliver Charlesworth

1 Answers

6
votes

Bind references to the Base subobjects, and compare them with normal operator syntax. An example:

class Base { /*...*/ };

bool operator==(const Base&, const Base&);

class Derive : public Base
{
    friend bool operator==(const Derive&, const Derive&);
private:
    int mem_;
};

bool operator==(const Derive& d1, const Derive& d2)
{
    return static_cast<const Base&>(d1) == static_cast<const Base&>(d2)
           && d1.mem_ == d2.mem_;
}

Warning: A setup like this will silently slice if you accidentally compare a Base to a Derive. If the base class must be comparable, it might be worth setting up a virtual comparison mechanism.