Login | Register   
RSS Feed
Download our iPhone app
Browse DevX
Sign up for e-mail newsletters from DevX

By submitting your information, you agree that devx.com may send you DevX offers via email, phone and text message, as well as email offers about other products and services that DevX believes may be of interest to you. DevX will process your information in accordance with the Quinstreet Privacy Policy.

Tip of the Day
Language: C++
Expertise: Intermediate
Sep 24, 1999



Building the Right Environment to Support AI, Machine Learning and Deep Learning

Guidelines for Overloading the + Operator

The built-in + operator is a binary operator that takes two arguments of the same type and returns the sum of its arguments without changing their values. In addition, + is a commutative operator. This means that you can swap the operands' positions and still get the same result. Likewise, an overloaded version of operator + should reflect all these characteristics.

When overloading +, you can either declare it as a member function of its class or as a friend function. For example:

class Date
  Date operator +(const Date& other); //member function
class Year
  friend Year operator+ (const Year y1, const Year y2); //friend
Year operator+ (const Year y1, const Year y2);  
The friend version is preferred because it reflects symmetry between the two operands. Since built-in + does not modify any of its operands, the parameters of the overloaded + are declared const. Finally, overloaded + should return the result of its operation by value, not by reference.
Danny Kalev
Comment and Contribute






(Maximum characters: 1200). You have 1200 characters left.



Thanks for your registration, follow us on our social networks to keep up-to-date