HomeComputer programmingC++: Operator Overloading (Slightly More Complex)

C++: Operator Overloading (Slightly More Complex)

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)

RELATED ARTICLES

1 COMMENT

LEAVE A REPLY

Please enter your comment!
Please enter your name here

- Advertisment -

Most Popular

Recent Comments

Cleveland Furia on How to Clear Google Activity
Sid Wohlfarth on How to Clear Google Activity
Riley Magsayo on How to Clear Google Activity
สมัครรับเครดิตฟรี ทันที on How to improve Remote Desktop Protocol Performance
Neal Wangstad on How to Clear Google Activity
Slavcho Andov on How to install Ubuntu
Slavcho Andov on How to fix bad sectors
Sheraz Ali on How to Backup Android