1

Consider the following code:

// Only prefix operators
struct prefix
{
    prefix& operator--() { return *this; }
    prefix& operator++() { return *this; }
};

// Try to represent prefix & postfix operators via inheritance
struct any : prefix
{
    any operator--(int) { return any(); }
    any operator++(int) { return any(); }
};

int main() {

    any a;

    a--;
    a++;
    --a; // no match for ‘operator--’ (operand type is ‘any’)
    ++a; // no match for ‘operator++’ (operand type is ‘any’)

    return 0;
}

I tried to create a hierarchy of classes. The base class, only to realize the prefix increment/decrement operators. And to add a postfix versions in derived class.

However, compiler can not find the prefix operation for the derived class object.

Why is this happening, why prefix operators are not inherited?

αλεχολυτ
  • 4,792
  • 1
  • 35
  • 71

1 Answers1

4

Use the following to import the hidden operator-- and operator++ of the prefix class:

struct any : prefix
{
    using prefix::operator--;
    using prefix::operator++;
    any operator--(int) { return any(); }
    any operator++(int) { return any(); }
};

Live demo

This is probably a terrible idea, but at least it will compile.

Shoe
  • 74,840
  • 36
  • 166
  • 272
  • 1
    Somehow, I perceived the prefix and postfix forms as different operators. But it's the same thing turns out that the function `f(int)` in the base class and `f(double)` in a derived. Thanks a lot. – αλεχολυτ Jul 02 '14 at 14:22