- Constructors
- Error Handling
- The Concept of Scope
- Operator Overloading
- Multiple Inheritance
- Object Operations
- Conclusion
- References
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, there are times when 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.
String Concatenation
String concatenation is when two strings are combined to create a single string.
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. In fact, 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 and C# do not allow operator overloading.
Java does not allow the option of overloading operators. The language itself does overload the plus sign for string concatenation, but that's 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 not to confuse the people who will use the class by documenting and commenting properly.