What is operator overloading? Explain this concept and provide a suitable example.
/*Operator overloading is an important concept in C++. It is polymorphysm in which
an operator is overloaded to give user defined meaning to it. Overloaded operator
is used to perform operation on user-defined data type. Almost any operator can be
overloaded in C++. Operator that are not be overloaded are follows
- member selector - .
- sizeof
- ternary operator - ?
- member pointer selector - *
- scope operator - ::
Operator overloading can be done by implementing a function which can be
member function, non-member function or friend function
Following are some restrictions to be kept in mind while implementing operator
operator overloading
- Precedence and Associativity of an operator cannot be changed
- Arity cannot be changed. Unary operator remains unary, binary remains binary etc.
- No new operators can be created, only existing operators can be overloaded
- Cannot redefine the meaning of a procedure. You cannot change how inetgers are added
Reference - studytonight.com */
#include<iostream>
using namespace std;
class TwoInt
{
int a;
int b;
public:
//default constructor
TwoInt():a(0),b(0){}
//init constructor
TwoInt(int _a, int _b):a(_a),b(_b){}
//assign constructor
TwoInt(TwoInt& x):a(x.a),b(x.b){}
//member function operator++
void operator++()
{
a++;b++;
}
//member function operator--
void operator--()
{
a--;b--;
}
friend ostream& operator<<(ostream& os, TwoInt& tin);
friend TwoInt operator+ (TwoInt& x, TwoInt& y);
};
//non-member friend function operator<<
ostream& operator<<(ostream& os, TwoInt& tin)
{
return os<<tin.a<<" "<<tin.b;
}
//non-member friend function operator+
TwoInt operator+ (TwoInt& x, TwoInt& y)
{
TwoInt z(x.a+y.a,x.b+y.b);
return z;
}
int main()
{
TwoInt x(1,5);
cout<<"Output of primary TwoInt x is: \n";
cout<<x<<endl;
++x;
cout<<"Output of TwoInt x after operator++ is: \n";
cout<<x<<endl;
TwoInt y(12,15);
cout<<"Output of primary TwoInt y is: \n";
cout<<y<<endl;
--y;
cout<<"Output of TwoInt y after operator-- is: \n";
cout<<y<<endl;
TwoInt z;
cout<<"Output of TwoInt z after operator+ with x and y is : \n";
z=x+y;
cout<<z;
}
Comments
Leave a comment