Operator Overloading Polymorphism, Virtual Function
Operator Overloading Polymorphism, Virtual Function
}
void display()
{
cout<<"x="<<x<<"\n";
}
};
int main()
{
integer a,b(5),c(-7);
cout<<"b=";
b.display();
a=-b;
cout<<"-a=";
a.display();
cout<<"c=";
c.display();
a=-c;
cout<<"a=";
a.display();
return 0;
}
#include<iostream>
using namespace std;
class integer
{
private:
int x;
public:
integer (int y=0)
{
x=y;
}
integer operator ++()
{
++x;
}
integer operator ++(int)
{
x++;
}
void display()
{
cout<<x<<"\n";
}
};
int main()
{
integer a(5);
cout<<"a=";
a.display();
++a;
cout<<"after ++a;,a=";
a.display();
a++;
cout<<"after a++;,a=";
a.display();
return 0;
}
Overload binary operator
* / < <=
type operator operator_to_be_overloaded(formal argument)
{
Local variable
Statements
Return statement
}
Note that special member function used for overloading a binary
operator require one more argument of the class type. This is
because operator can operate on two object .
#include<iostream>
int main()
using namespace std;
{
class measure
measure m1(2,3),m2(4,10),m3;
{
cout<<"m1:";
private:
m1.display();
int feet;
cout<<"m2:";
float inches;
m2.display();
public:
m3=m1+m2;
measure (int f=0,float i=0)
cout<<"sum=";
{
m3.display();
feet=f;
return 0;
inches=i;
}
}
measure operator +(measure &m)
{
measure t;
t.feet=feet+m.feet;
t.inches=inches+m.inches;
if(t.inches>=12)
{
t.feet++;
t.inches-=12;
}
return (t);
}
void display()
{
cout<<feet<<"-"<<inches<<"\n";
}
};