C++ - 03
C++ - 03
Overloading refers to the use of same thing for different purpose. Function overloading is an
example of compile time polymorphism.
Using the concept of function overloading it creates a family of functions with one function name but
with different argument lists.
The function would perform different operation, depending on argument list in function call.
The correct function to be invoked is determined by checking the number and the type of the
arguments and not on the function type.
#include<iostream.h>
class A
{
public:
void area(int s)
{
cout<<s*s;
}
void area (int l, int b)
{
Cout<<l*b;
}
};
void main( )
{
A a1;
a1.area(5);
a1.area(5,10);
}
The mechanism of giving some special meaning to an operator is called as operator overloading.
C++ permits to add two variables of user defined data types with the same syntax as the basic types.
When an operator is overloaded, its original meaning is not lost.
To define an additional task to an operator, a special function called ‘operator function’ is used to specify the
relation of the operator to the class.
The process of overloading involves the following steps:
1) First create a class that defines the data type that is to be used in the overloading operation.
2) Declare the operator function operation op( ) in the public part of the class. It may be either a member
function or a friend function.
3) Define the operator function to implement the required operations.
• Syntax of an operator function:
#include<iostream.h>
#include<conio.h>
class space
{
private:
int x;
public:
space()
{
x=10;
}
void display ()
{
cout<<x;
}
void operator –( );
};
void space::operator -(void)
{
x = - x;
}
void main ( )
{
space s;
s.display ( );
-s;
cout<< “ –s:”;
s.display( );
}
i) Only existing operators can be overloaded. New operators cannot be created.
ii) The overloaded operator must have at least one operand that is of user defined type.
iii) The basic meaning of an operator cannot change ie. We cannot redefine the plus (+) operator to subtract one value
from the another.
iv) The overloaded operators must follow the syntax rules of original operators.
v) Unary operators, overloaded by means of a member function take no explicit arguments & return no explicit values.
vi) Unary operators, overloaded by means of a friend function take one reference argument.
vii) Binary operators overloaded through a member function takes one explicit argument. Binary operators overloaded
through a friend function takes two explicit arguments.
viii)When using binary operators overloaded through a member function, the left hand operator must be an object of
the relevant class.
ix) Binary arithmetic operators such as +, -, * and / must explicitly return a value. They must not attempt to change
their own arguments.