Home > Articles > Software Development & Management > Object Technology

  • Print
  • + Share This
This chapter is from the book

Operator Overloading

Some OO languages allow you to overload an operator. C++ is an example of one such language. Operator overloading allows you to change the meaning of an operator. For example, when most people see a plus sign, they assume it represents addition. If you see the equation

X = 5 + 6;

you expect that X would contain the value 11. And in this case, you would be correct.

However, at times a plus sign could represent something else. For example, in the following code:

String firstName = "Joe", lastName = "Smith";

String Name = firstName + " " + lastName;

You would expect that Name would contain Joe Smith. The plus sign here has been overloaded to perform string concatenation.

In the context of strings, the plus sign does not mean addition of integers or floats, but concatenation of strings.

What about matrix addition? You could have code like this:

Matrix a, b, c;

c = a + b;

Thus, the plus sign now performs matrix addition, not addition of integers or floats.

Overloading is a powerful mechanism. However, it can be downright confusing for people who read and maintain code. In fact, developers can confuse themselves. To take this to an extreme, it would be possible to change the operation of addition to perform subtraction. Why not? Operator overloading allows you to change the meaning of an operator. Thus, if the plus sign were changed to perform subtraction, the following code would result in an X value of –1:

x = 5 + 6;

More recent OO languages like Java, .NET, and Objective-C do not allow operator overloading.

Although these languages do not allow the option of overloading operators, the languages themselves do overload the plus sign for string concatenation, but that’s about it. The designers of Java must have decided that operator overloading was more of a problem than it was worth. If you must use operator overloading in C++, take care by documenting and commenting properly not to confuse the people who will use the class.

  • + Share This
  • 🔖 Save To Your Account