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?
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(); }
};
This is probably a terrible idea, but at least it will compile.