Pure virtual function in abstract class with return type of base/derived type

2k views Asked by At

I wish to make each derived class of a base class to implement a function (in this case the postfix operator) which has the derived class' type as return type, as this:

class A {
    virtual A operator++(int) =0;
}

class B : public A {
    B operator++(int);
}

This generates errors of the kind return type 'A' is an abstract class. What to do? As far as I understand the postfix must return the actual type and not a reference/pointer to the type.

1

There are 1 answers

2
vsoftco On

What about using the CRTP pattern:

template <typename T>
class A {
    virtual T operator++(int) =0;
};

class B : public A<B> {
    B operator++(int) override
    {
        // do something here
        return *this; 
    }
};

PS: just saw that @Marco A. posted a link with a similar approach. I will keep my answer for completeness, don't feel any pressure to vote it.