Search code examples
c++inheritancec++17virtual-functionsabstract-base-class

Abstract base class virtual pure method that takes itself as a parameter


Apologies for any poor wording, I'm not quite sure how to express the question.

I have a base class A, which has a pure virtual operator+= which takes an instance of itself. In the derived class B I'd like to override operator+= of the base class such that it takes an instance of B (rather than A).

// Abstract base class
template <class T>
class A
{
    A() = default;

    virtual A<T>& operator+=(const A&) = 0;
}

// Derived class
template <class T>
class B : public A<T>
{
   T some_field = 3.14159;

   B(const T x) : A(), some_field(x) {}

   B<T>& operator+=(const B& b) override
   {
       this.some_field += b.some_field;

       return (*this);
   }
}

I do understand why this doesn't work; the two methods are different functions because they expect different arguments. However, I assume that there must be some way to guarantee that any class derived from A will implement operator+= in which it takes an instance of the derived class as the argument.

virtual operator+=(const <this_class_type>&) = 0;

Please could you offer a solution to this? Thanks very much!


Solution

  • One way to achieve this would be using T for the parameter:

    template<typename T>
    class IBase
    {
    public:
        virtual IBase& operator+=(const T& Instance) = 0;
    };
    
    class CDerived : IBase<CDerived>
    {
    public:
        IBase& operator+=(const CDerived&) override
        {
            return *this;
        }
    };
    
    class COtherDerived : IBase<COtherDerived>
    {
    public:
        IBase& operator+=(const COtherDerived&) override
        {
            return *this;
        }    
    };
    
    int main(int argc, char** argv)
    {
        CDerived Derived1, Derived2;
        Derived1 += Derived2;
        COtherDerived Derived3;
        // Derived3 += Derived1; <-- Will not compile
    }