How to override an operator for polymorphism

  • A+

Can anyone explain to me what I'm doing wrong here?

struct X {     int x{};      explicit X(int x) : x(x) {}      virtual X &operator++() = 0; };  struct OK : X {     int ok{};      explicit OK(int ok) : X(ok), ok(ok) {}      X &operator++() override {         ok += 10;         return *this;     } };  struct MU : X {     int mu{};      explicit MU(int mu) : X(mu), mu(mu) {}      X &operator++() override {         mu *= 5;         return *this;     } };  int main() {     X *x_base = new OK(0);     ++x_base;     std::cout << x_base->x;     return 1; }; 

All that I'm trying to do is to use the idea of polymorphism for operators, in special the operator++. I want to have a result something like this:

Base* base = new Derivate();

++base <--- the ++ should be called from the Derivate class

Base* base2 = ned Derivate_2();

++base <--- the ++ should be called from the Derivate_2 class


The current solution to my problem is to use ++(*base) which I know about this already.

But is there any other way to do ++base instead of ++(*base)?

Thanks for the help :)


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; }; 


:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: