Operatoroverloading
Operatoroverloading
Operator Overloading
C++ language.
Create a class that defines the data type that is to be used in the
overloading operation.
Declare the operator function operator op() in the public part
of the class.
Define the operator function to implement the required
operations.
Overloading Unary Operators
Consider unary minus operator (changes the sign of the
operand)
members. Accept the date from the user and display it.
Overload the increment and decrement operators for
displaying the next and previous date for the given date.
Overloading Binary Operators
As a unary operator is overloaded we can also overload a binary
operator.
For e.g: A binary operator + can be overloaded to add two objects
rather than adding two variables.
Using operator overloading a functional notation,
C = sum(A, B);
Can be replaced by,
C = A + B;
Overloading Binary Operators
class complex
{
float x;
float y;
public:
complex(){}
complex(float real, float imag)
{
x = real;
y = imag;
}
complex operator + (complex);
void display(void);
};
Overloading Binary Operators
complex complex :: operator + (complex c)
{
complex temp;
temp.x = x + c.x;
temp.y = y + c.y;
return (temp);
}
void complex :: display(void)
{
cout << x << “ + j “ << y ;
}
Overloading Binary Operators
int main()
{
complex C1, C2, C3;
C1 = complex(2.5, 3.5);
C2 = complex(1.6, 2.7);
C3 = C1 + C2; // invokes operator+() function
cout << “ C1 = “; C1.display();
cout << “ C2 = “; C2.display();
cout << “ C3 = “; C3.display();
return 0;
}
Overloading binary operators using
Friends
Friend functions may be used in place of member functions
for overloading a binary operator.
A friend function requires two arguments to be explicitly
passed to it, while a member function requires only one.
For e.g:
complex operator + (complex);
C3 = C1 + C2;
Is equivalent to
C3 = operator+(C1, C2);
Overloading Stream Insertion and
Extraction Operators
It is possible to overload the stream insertion (<<) and
their code number, total items in the stock and the cost of
each item.
Example.
Type conversion summary
Short Answer Questions
Why is it necessary to overload and operator?