Interesting observation about C++ operator overloading.

I don’t know why it didn’t dawn on me that this would work. After all, it’s not like I’ve been using C++ for the past 18-mumble-years. (Oh, wait; I have. Meh.)

So we define a class AClass, BClass and CClass such that AClass has an operator that converts it to BClass and CClass, and BClass has an operator that converts it to CClass. (Call AClass “integer”, BClass “double” and CClass “std::complex”.)

If we then define three operator + implementations:

AClass operator + (const AClass &a, const AClass &b);
BClass operator + (const BClass &a, const BClass &b);
CClass operator + (const CClass &a, const CClass &b);

Then we get automatic promotion to the appropriate type (AClass, BClass or CClass), regardless of what mixture of classes we use. Thus:

AClass a(5);
BClass b(3.3);
CClass c = a + b;

will set c = 8.3 + 0i.

I mean, this behavior makes complete sense. I just never thought of using this feature for my own code, until now.

Leave a Reply

Please log in using one of these methods to post your comment: Logo

You are commenting using your account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s