Probably the best example of the power of operator overloading is the BigNumber class in Java and its equivalent in .NET, BigInteger. First, the purpose of this class (in both class libraries) is to represent numbers larger than a 64-bit integer can hold. Obviously, this doesn't come up that often but if you need it, you need it. In Java, which does not allow operator overloading, you have to do arithmetic with BigNumber objects like this:
Code: Select all
BigNumber result = bNumber1.add(bNumber2).multiply(bNumber3).subtract(4);
In .NET, which does allow operator overloading, you would do the same this way:
Code: Select all
BigInteger result = (bInt1 + bInt2) * bInt3 - 4;
It is pretty obvious which is better lol.
But as usual, with great power comes great responsibility. Operator overloading can be horribly abused, which is why it isn't allowed in Java. You don't see this much in C#, but in some legacy C++ code from the days before strong software engineering principles were the norm, you will find people using operator overloading in extremely confusing ways. It is intended to be used for operators that are logical to the situation, such as overloading +, -, *, etc. for BigInteger. For example, overloading -, +, * makes no sense for your Player class. What on earth does player1 + player2 mean? All you are doing at that point is making your code less legible.