Search code examples
c++polymorphismoperator-overloading

C++ operator overloading and polymorphism


Do polymorphism and operator overloading mix together?

You can't do polymorphism without pointers, as it is explained in this answer and also you can't do operator overloading with pointers as explained here. So there really isn't any way to do this, right?


Solution

  • Yes there is. You didn't read the answers properly.

    Here is a short demo:

    #include <iostream>
    using namespace std;
    
    struct X
    {
        int value;
        virtual void operator += (int x)
        {
            value += x;
        }
    };
    
    struct Y : X
    {
        virtual void operator += (int x)
        {
            value *= x;
        }
    };
    
    void do_stuff(X& x)
    {
        x += 10;
        cout << "Final value " << x.value << endl;
    }
    
    int main()
    {
        X x;
        x.value = 10;
        Y y;
        y.value = 10;
        do_stuff(x);
        do_stuff(y);
    
        return 0;
    }
    

    I'm not implying that this is a good idea, or that it's practical. It's simply just possible.