C++: Main Operator Overloading
How to Overload the common operators: =, +, -, *
Overloading an operator allows for custom operations on your own objects.
*Say you want to add to person objects (ex. marriage)?
-then you overload the + operator and define what is to be done when you add the objects.
*For all my examples i will be using Person as the class which is my personally defined object.
+ Operator:
The + operator takes 2 operands if it is declared outside of the Person class:
//+Operator Overloader
Person& operator+(const Person& p1, const Person& p2){
//code goes goes in here
}
The + operator takes 1 operand if it is declared inside the Person class:
//+Operator Overloader
Person& operator+(const Person& p2){
//code goes goes in here
}
*The object p1 can be accesed as a pointer as well with the keyword this.
- Operator:
The – operator takes 2 operands if it is declared outside of the Person class:
//-Operator Overloader
Person& operator-(const Person& p1, const Person& p2){
//code goes goes in here
}
The – operator takes 1 operand if it is declared inside the Person class:
//-Operator Overloader
Person& operator-(const Person& p2){
//code goes goes in here
}
*The object p1 can be accesed as a pointer as well with the keyword this.
* Operator:
The * operator takes 2 operands if it is declared outside of the Person class:
//*Operator Overloader
Person& operator*(const Person& p1, const Person& p2){
//code goes goes in here
}
The * operator takes 1 operand if it is declared inside the Person class:
//*Operator Overloader
Person& operator*(const Person& p2){
//code goes goes in here
}
*The object p1 can be accesed as a pointer as well with the keyword this.
You may wish to write 2 or more of any of these overloaders, depending on the nature of your program, to include adding, subtracting and multiplying by integers, Strings or other objects.
(eg: i personally wrote a Polynomial class as an assignment in University, to apply scalars to Polynomials as well as multiply polynomials requires 2 * operator overloaders.)
= Operator:
Personl operator=(const Person& eqR){ //R for right-hand side of = sign
//code would be similar to:
Person *p = new Person(); //requires a default constructor
//copy all fields from eqR to p here
//(using p-> to assign left side, and this-> for right side)
return *p; //incase you wish to assign an x = y = z
}
<< Operator:
ostream& operator<<(ostream& out, const Polynomial& p){
//your cout<< statements will be out<< inside this function
return out; //must return the ostream object to continue cout through the rest of your program
}
*NOTE the use of out to replace cout here, thus your code looks similar.
the ostream object must be returned or risk losing the use of cout<< for the rest of your program.
That's all there is to it!!
Questions/Comments: william_a_wilson@hotmail.com
-William. ยง (marvin_gohan)





