Skip to content
avatar

Operator Overloading

Something that had been bothering me for a month just clicked in my brain and I had to write it down before it wandered off somewhere. No one who regularly reads this blog will understand, but here goes.

C++ has operator overloading that leads to code that no one understands. If I define a class Car and a class Tire, I can override some random math operator like, say, += on Car, and make it so that that sets the Tire of my car.


Car myCar = new Car();
myCar += new Tire(); //calls my "+=" operator, but this code is unreadable

C# has properties, which means that I can define a class Car that has a property Tire, so now I can define the relation between the car and the tire, and write code like this:


Car myCar = new Car();
myCar.Tire = new Tire(); //calls Car's property code for "Tire"

But Ruby has operator overloading of a different sort than C++, which gives it a lot of the clarity that C# properties exhibit, so in Ruby I write:


myCar = Car.new();
myCar.tire = Tire.new(); //calls Car's "tire=" method

C++ has operator overloading, but not in a way that makes sense; you can create the relations your class has with those classes you happen to know about when you write your class, but there are no relationships, which is what programming in large projects is all about.

Moral of the story: shortcuts that make your code less readable are only short until you have to re-read your code, which may be tomorrow or may be next year. It’s generally best to avoid such “shortcuts,” which go by such names as “C++ operator overloading,” “assignments in conditions,” and “Perl.”