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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With