Operator overloading
Operator overloading is a type of a compile time polymorphism in C++. In C++ an operator is a symbol that tells the compiler to perform specific task. Every operator have their own functionality to work with data types. Class is user-defined data type so, compiler doesn't understand, how to use operators with user-defined data types. To use operators with user-defined data types, they need to be overload according to a programmer's requirement.
Operator overloading is a way of providing new implementation of existing operators to work with user-defined data types.
C++ provides a wide variety of operators to perform operations on various operands.
C++ allows almost all operators to be overloaded in which case at least one operand must be an instance of a class.
C++ allows most operators to be overloaded for user-defined types(classes).
The following operators can be overloaded:
The following can not be overloaded:
Defining operator overloading:-
To define an additional task to an operator, we must specify what it means in relation to the class to which the operator is applied. This is done with the help of a special function, Called operator function, which describe the task.
The general form of operator function is:-
Return type classname
:: operator op(arglist)
{
Function body // task defined
}
|
Where return type is the type of value returned by the specified
operation and op is the operator being overloaded is applied.
The op is preceded by the keyword operator. Operator op is the function name.
complex complex ::
operator+(complex c)
|
Where first complex
is return type so, it
return a complex value and second complex is classname.
In this example we overload a + operator
Operator overloading example:-
#include<iostream.h>
#include<conio.h>
#include<stdio.h>
class complex
{
float r; // real part
float i; // imaginary part
public:
complex() //constructor 1
{}
complex(float real,float imag) // constructor 2
{
r=real;
i=imag;
}
complex operator+(complex);
void display(void);
};
complex complex ::
operator+(complex c)
{
complex temp;
temp.r = r+c.r;
temp.i = i+c.i;
return(temp);
}
void complex :: display(void)
{
cout<<r<<"+j"<<i<<endl;
}
void main()
{
complex c1,c2,c3;
c1 = complex(1.5 , 3.5);
c2 = complex(2.5 , 4.5);
c3 = c1+c2;
cout<<"c1 = ";
c1.display();
cout<<endl<<"c2
= ";
c2.display();
cout<<endl<<"c3
= ";
c3.display();
getch();
}
|
Where, In this program
we using constructor and, there are four member function two function are
constructor function, one operator function and one display function. The class
of the program is complex, and
two constructor function are:-
First constructor function is blank and second is use to call the data member of the class.
The operator function is:-
complex complex ::
operator+(complex c)
{
complex temp;
temp.r = r+c.r;
temp.i = i+c.i;
return(temp);
}
|