Overloading Operator + the Right Way
By Danny Kalev, C++ Pro

User-defined types such as string, date, complex and file often overload the binary + operator to perform some sort of concatenation, addition or merging of two objects. However, a proper implementation of operator + poses several challenges in terms of design, implementation and performance. In the following sections, I will show how to choose the right strategies for overloading this operator for user-defined types in general.

Consider the following expression:


int x=4+2;
The built-in + takes two operands of the same type, adds them and returns an rvalue 6 which is assigned to x. We can conclude that the built-in + is a binary, symmetric and commutative operator. It produces a result of the same type as its operands'. As a rule, when you overload an operator for a user-defined type, retain the characteristics of the corresponding built-in operator.



Overloading the + operator for a user-defined type is a common programming task. However, since C++ offers several implementation approaches, it's relatively easy to make design mistakes that have adverse effects on code correctness, performance and compatibility with Standard Library components.



Analyze the characteristics of the built-in operator and try to imitate them in the corresponding overloaded operator.

  
Next: Choosing Between a Member Function and a non-Member Function

Introduction
Choosing Between a Member Function and a Non-Member Function
Implementation

Return to Get Help with C/C++ Page

Return to Main Get Help Page


 




Find Out More

All DevX 10-Minute Solutions for C/C++

DevX Tip: Guidelines for Overloading the + Operator

DevX Tip: What are Lvalues and Rvalues?

STL Library Programmer's Guide


TALK BACK
Operator overloading was deliberately omitted from Java because its creators considered it a source of "unnecessary complication." However, C# does support operator overloading, just as does C++. What is your stance regarding operator overloading? Is it an indispensable feature or a source of "unnecessary complication," as Java designers claimed?


Sponsored Links