C++: Operator Overloading (slightly more complex)

Contributor Icon Contributed by William_Wilson Date Icon February 27, 2006  
Tag Icon Tagged: Computer programming

How to Overload the operators: ++(int), (int)++, –(int), (int)–


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

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 and 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 and the postfix requires the object be changed, but the original returned.

Slightly more thinking, but relatively straight forward, enjoy!

Question/Comments: william_a_wilson@hotmail.com
-William. ยง (marvin_gohan)

Previous recipe | Next recipe |
 
blog comments powered by Disqus