Operator overloading in C++ programming is used to overload or redefines the function by using (operator) keyword. It is used to perform the operation based on user-defined data type.
#include<iostream.h>
#include<conio.h>
class complex
{
private:
int real, img;
public:
complex()
{
real = 0;
real = 0;
}
complex(int newReal, int newImg)
{
real = newReal;
img = newImg;
}
complex add(const complex & c1) //this is function and 'c1' is object.
{
complex t; //'t' is object of class 'complex'.
t.real = real + c1.real; //adding and assigning to 'real'.
t.img = img + c1.img; //adding and assigning to 'img'.
return t; //returning 't' value.
}
void show()
{
cout<<"real is: "<<real<<endl;
cout<<"img is: "<<img<<endl;
}
};
void main()
{ //'a1, a2 and a3' is objects of class 'complex'.
complex a1(5, 6); //calling and passing arguments.
complex a2(3, 4); //calling and passing arguments.
complex a3;
a3 = a2.add(a1); //adding 'a1' and 'a2' and assigning to 'a3'.
a3.show(); //calling 'show()' function.
getch();
}
#include<iostream.h>
#include<conio.h>
class cls
{
private:
int first, second, third;
public:
cls()
{
first = 0;
second = 0;
third = 0;
}
cls(int newFirst, int newSecond, int newThird)
{
first = newFirst;
second = newSecond;
third = newThird;
}
cls operator +(const cls & x) //U also use '-', '*' etc here.
{
cls z; //'z' is object of class 'cls'.
z.first = first + x.first; //adding and assigning again to 'first'.
z.second = second + x.second; //adding and assigning again to 'second'.
z.third = third + x.third; //adding and assigning again to 'third'.
return z; //returning 'z' value.
}
void show()
{
cout<<"first is: "<<first<<endl;
cout<<"second is: "<<second<<endl;
cout<<"third is: "<<third<<endl;
}
};
void main()
{ //'c1, c2 and c3' is objects of class 'cls'.
cls c1(5, 8, 9); //calling and passing arguments.
cls c2(3, 10, 1); //calling and passing arguments.
cls c3;
c3 = c2 + c1; //adding 'c2' and 'c1' object and assigning to 'c3'.
c3.show();
getch();
}