Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

c++ operator overloading & 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 is no way to do this, right?

like image 221
titus Avatar asked Dec 08 '22 23:12

titus


1 Answers

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.

like image 195
Šimon Tóth Avatar answered Jan 30 '23 01:01

Šimon Tóth