2022-11-20

C++ Can I create an interface which calls method implemented specifically in child class, through operator override implemented in the interface?

apologies in advance if this question is stupid but:

I have an interface:

template <class T>
class IEqualCompare {
public:
    virtual bool IsEqual(const T b) = 0;
    bool operator== (const T b) { return this->IsEqual(b); }     //Both are implemented in cpp file
    bool operator!= (const T b) { return !(this->IsEqual(b)); }
};

And a class:

class Dimentions : IEqualCompare<Dimentions> {

...


bool IsEqual(const Dimentions b) { //IsEqual logic for this specific class }

...

}

I would like to only implement IsEqual method for each child class of IEqualCompare, as the logic within the operator overloads (==, !=) is the same for any IEqualCompare derived class.

Up until now I have always simply defined both operator overrides as virtual and implemented them inside each class, but as the logic should be always the same I wanted to know if this is possible or is it bad programming.

Thanks in advance for any answers.



No comments:

Post a Comment