How to override an operator for polymorphism
In these two lines,
X *x_base = new OK(0);
++x_base;
you create a pointer to the new instance, and you then increment the pointer, not the pointee. The increment operator of your class hierarchy is never called, instead, this invokes the builtin increment operator for pointers. You can fix that by dereferencing the pointer first:
++*x_base; // or ++(*x_base), might be more readable
You can also work with references instead of pointers, which allows for an increment syntax without the need to derefence a pointer, e.g.
OK ok(0);
X& x_base = ok;
++x_base; // now, x_base is a reference, no need to dereference it
Note that the implementation of the operator overload that is called doesn't change the value of X::x
. The std::cout << x_base->x;
after the increment suggests that you expect the value to be non-zero.
To solve your second question you need to write a wrapper for your pointer class. Something like
class XPtr
{
public:
XPtr(X* p) : ptr(p) {}
X* operator->() { return ptr; }
X& operator*() { return *ptr; }
XPtr& operator++() { ++*ptr; return *this; }
private:
X* ptr;
};
int main() {
XPtr x_base = new OK(0);
++x_base;
std::cout << x_base->x;
return 1;
};