1

Take following piece of code as an example:

template<class Derived>
struct base {
    Derived operator++(int){
        auto tmp = static_cast<Derived &>(*this);
        ++static_cast<Derived &>(*this);
        return tmp;
    }
};

struct der : public base<der> {
    der &operator++(){
        return *this;
    }
};

int main(){
    der d;
    d++;/// <<< compilation error here
}

I get following error from compiler:

error: no 'operator++(int)' declared for postfix '++' [-fpermissive]

Why isn't my postfix operator visible for compiler? Does it contain some kind of error or is it some unknown to me C++ feature? Can this code be fixed so that postfix operator++ will work as expected?

bartop
  • 9,971
  • 1
  • 23
  • 54

2 Answers2

3

Your two functions have the same name, operator++. It's just spelled differently from a function named with an identifier. The rule for a class member lookup is that by default, if a member with the name is found in a derived class, the base class is not checked. The derived member "hides" the base member.

The usual way to avoid hiding a base class function with a different signature, and allow overload resolution to pick the best function, is with a using-declaration:

struct der : public base<der> {
    der &operator++(){
        return *this;
    }
    using base<der>::operator++;
};
aschepler
  • 70,891
  • 9
  • 107
  • 161
1

Replace the name operator++ with the name f (that is try the same thing with an ordinary member function). You’ll have the same problem. The compiler finds the named function in der, so it doesn’t look in base<dir>. Overloading only occurs among functions defined in the same scope.

Pete Becker
  • 74,985
  • 8
  • 76
  • 165