Operator overloading in C++
In C++ we have operators for performing various things.
For doing operations on premitive data types there are many operator defined.
- + - * ( ) for doing any type of mathematical operations.
- new, delete can be used for memory related operations.
What if we have some user defined data types?
We can perform operations on them to by overloading those operators !
Hence do things to our user-defined data type.
Say adding up two time stamps, or two complex numbers!
For example:
Complex number a + ib real and imaginary parts of a complex number.
How do we add two such numbers?
5+ 7i
2+9i
==>7 + 16i
How can we do this programmatically?
Operator overloading!
class Complex{
private:
int real;
int img;
public:
Complex(int r = 0, int i = 0){
real = r;
img = i
}
}
int main(){
Complex c1(3,7)
Complex c2(5,4)
Complex c3;
}
If we can use our + we could have done this: c3 = c1 + c2
To produce a result of 8 + 11i stored in c3
But one obvious thing and logically possible thing we could do is
create a function to do this operation and make use of it everywhere instead of the + sign!
Considering add to be a function that does our job we can have:
c3 = c1.add(c2)
or c3 = c2.add(c1) Both are same, its like two people c1 and c2 adding up the money, either c1 will add the money or c2 will.
Note that object on whom the function is called c1 in this case has its own img and real parts too.
Complex add(Complex x){
Complex temp;
temp.real = real + x.real
temp.img = img + x.img
return temp
}
Now what if I change the name of my function to say
operator+ ?
c3 = c1.operator+(c2)
Now here comes the key point, 'operator' is a special keyword recognized by C++.
Now, c3 = c1 + c2 Can be written! Because operator is a special key word!
So the final program to overload the + operator will be:
class Complex {
private:
int real;
int img;
public:
Complex(int r = 0, int i = 0)
{
real = r;
img = i;
}
void display()
{
cout << real <<ā+ iā<< img << endl;
}
Complex operator+(Complex c)
{
Complex temp;
temp.real = real + c1.real;
temp.img = img + c1.img;
return temp;
}
};
int main()
{
Complex c1(5, 3), c2(10, 5), c3;
c3 = c1 + c2;
c3.display();
}