What is operator overloading?

 
 

Operator overloading allows existing C++ operators to be redefined so that they work on objects of user defined classes. The goal of operator overloading should be to improve the readability of code that uses a class. However, it should be used only in ways that are semantically familiar to users. For instance, it would be nonintuitive to use operator+ for subtraction.
The only C++ operators that can't be overloaded are dot (.), .*, arithmetic if (?:), size (sizeof), typeid, and ::. The goal of operator overloading is to make the class easier to understand.
Operators are overloaded by creating operator functions. It is created using the keyword operator. These functions can either be member of a class or then they have to be friend functions.
Syntax:
returntype class-name::operator#(arg-list)
{
}
E.g. class Complex
{
private:
float real;
float imaginary;
public:
Complex operator+ (Complex);
};
//overloaded + operator for class Complex
Complex Complex::operator+ (Complex c)
{
Complex tmp;
tmp.real = this.real + c.real;
tmp.imaginary = this.imaginary + c.imaginary;
return temp;
}

Re: What is operator overloading?

operator overloading is to provide additional feature to already existing c++ data types.
normally arthimatic operations are only performed to pre-defined operations,these are not work to user defined data types like objects through operator overloading we can provide arithmetic operations to objects.
in c++ through operator overloading we can achieve polymarphism concept
operator overloading can be done by two types of functions.
(1) Member Function.
(2) Friend Function.
Rules while passing the arguments to functions.
Unary Binary
Member Function -- 1
Friend Function 1 2
example with Member function
class A
{
public:
int x;
void get()
{
cout<
cin>>x;
}
A add operator +(A);
void prnt()
{
cout<
}
}
A A::add operator(A a)
{
A c;
c.x=x+a.x;
}
void main()
{
A u,v,w;
u.get();
v.get();
w=u+v;
w.prnt();
}
example with Friend function
class A
{
public:
int x;
void get()
{
cout<
cin>>x;
}
A friend add operator +(A);
void prnt()
{
cout<
}
}
A add operator(A r,A a)
{
A c;
c.x=r.x+a.x;
}
void main()
{
A u,v,w;
u.get();
v.get();
w=u+v;
w.prnt();
}