C++: Operator Overloading (Slightly More Complex)

Posted February 27, 2006 by William_Wilson in Computer programming

This tech recipe explains how to Overload the operators: ++(int), (int)++, –(int), (int)–.


The key is to know the action of these operators on the integers for which they are supplied.

For coding examples, I will again be using Person as my example class. Perhaps ++ or — increments or decrements the number of friends a particular person has.

ex:
int i = 0;
++i = 1;
i++ = 1; //result is old value
i = 2; //next time i is used, reveals the new value

–i = 1;
i– = 1; result is still old value
i = 0; //next time i is used, reveals the new value

No parameters are supplied in either case. The prefix versions are straight forward:
Prefix ++ | ++(int):

//++Operator Overloader - prefix
Person& operator++(){
this->friends = this->friends+1; //assuming Person class has a field friends.
return *this; return in the case of an assignment as well
}

Prefix — | –(int):

//--Operator Overloader - prefix
Person& operator--(){
this->friends = this->friends-1; //assuming Person class has a field friends.
return *this; return in the case of an assignment as well
}

*You may also wish to check for a result of this->friends == 0 in this method.

The postfix version may not appear so obvious:
Postfix ++ | (int)++:

//++Operator Overloader - postfix
Person& operator++(int){ //the int here specifies as postfix
//the int is NOT a parameter
Person *p = new Person(*this); //requires a copy constructor
//p is now a copy of the given Person
this->friends = this->friends+1; //update this Person
return *p; return copy before modification
}

*We must return the copy for use. The postfix requires the object be changed, but the original returned.

Postfix — | (int)–:

//--Operator Overloader - postfix
Person& operator--(int){ //the int here specifies as postfix
//the int is NOT a parameter
Person *p = new Person(*this); //requires a copy constructor
//p is now a copy of the given Person
this->friends = this->friends-1; //update this Person
return *p; return copy before modification
}

*We must return the copy for use. The postfix requires the object be changed, but the original returned.

Slightly more thinking, but relatively straight forward, enjoy!

Question/Comments: [email protected]
-William. ยง (marvin_gohan)

The Conversation

Follow the reactions below and share your own thoughts.