0% found this document useful (0 votes)
2 views

Operator Overloading

Uploaded by

Abdullah
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views

Operator Overloading

Uploaded by

Abdullah
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 6

Operator overloading

Operator overloading
 class complex
 { private:
 int a,b;
 public:
 void setdata(int x, int y)
 { a=x; b=y; }
 void showdata()
 { cout<<"a="<<a<<" b= "<<b; }
 complex operator +(complex c)
How to make + a friend
 { complex temp;
function ???
 temp.a=a+c.a;
 temp.b=b+c.b;
 return (temp);
 }
 };
 int main()
 {
 complex c1,c2,c3;
 c1.setdata(3,4);
 c2.setdata(5,6);
 c3=c1+c2;
Here c1 is caller object, c2 is the
 c3.showdata();
 getch();
argument.
 return 0;
 }

Operator overloading as friend function.
void showdata()
{ cout<<"a="<<a<<" b= "<<b; }
friend complex operator +(complex, complex);

};
complex operator +(complex X, complex Y);
When ever we overload a binary
{
complex temp;
operator as friend function we
temp.a=X.a+Y.a; have to send two arguments.
temp.b=X.b+Y.b;
return (temp);
}
int main()
{
complex c1,c2,c3;
c1.setdata(3,4);
c2.setdata(5,6);
c3=c1+c2; Here both c1 & c2 are
c3.showdata(); arguments.
getch();
return 0;
}
Operator overloading as friend function.

 Now overload unary operator (++, pre


increment) using friend function.
friend complex operator ++(complex);

};
complex operator ++(complex X)
{
complex temp;
temp.a=++X.a;
temp.b=++X.b;
return (temp);
}
int main()
{
complex c1,c2,c3;
c1.setdata(3,4);
c2.setdata(5,6);
c3=++c1; //c3=c1.operator ++()
c3.showdata();
getch();
return 0;
}
Operator overloading as friend function.

 class person
{
 private:
 int id;
 string name;
 float gpa;
 public:
 friend void display(person *s);
 };
Operator overloading as friend function.

 void display (person *s)


 { int main()
 cin >> s->id; {
 cin>> s->name; person a;
 cin>> s->gpa; display(&a);
 cout <<"output"<<endl; }

 cout<< “Id:”<<s->id<<endl;
 cout<< “Name:”<<s->name<<endl;
 cout<<“GPA:”<<s->gpa<<endl;
 }

You might also like