Login | Register   
Twitter
RSS Feed
Download our iPhone app
TODAY'S HEADLINES  |   ARTICLE ARCHIVE  |   FORUMS  |   TIP BANK
Browse DevX
Sign up for e-mail newsletters from DevX


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

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
{
public:
  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.

 

 

Sitemap