Operator Overloading
Operator Overloading
1) Declaration
Body
3)Calling/invoke operator
Syntax
Ex
-s1;
#include<iostream.h>
#include<conio.h>
class temp
{
int x,y,z;
public:
void getdata(int a,int b,int c)
{
x=a;
y=b;
z=c;
}
void display()
{
cout<<”x=”<<x<<endl;
cout<<”y=”<<y<<endl;
cout<<”z=”<<z<<endl;
}
void operator –() // operator overloading function
{
x=-x;
y=-y;
z=-z;
}
};
temp t;
t.getdata(10,-20,30);
cout<<”before overloading”;
t.display();
-t; // invoke operator overloading function
cout<<”after overloading”;
t.display();
getch();
return 0;
}
out put
before overloading
x=10
y=-20
z=30
after overloading
x=-10
y=20
z=-30
#include <iostream>
#include<conio.h>
class Height
{
public:
int feet, inch;
Height() // default constructor
{
feet = 0;
inch = 0;
}
Height(int f, int i) //parameterized constructor
{
feet = f;
inch = i;
}
// Overloading (+) operator to perform addition of
// two distance object using binary operator
int main()
{
Height h1(3, 7);
Height h2(6, 1);
Height h3;
h3 = h1 + h2; //Use overloaded operator
cout << "Sum of Feet & Inches: " << h3.feet << "'" << h3.inch << endl;
getch();
return 0;
}
Output: