Overloading In C++
Creating two or more members that have the same name but are
different in number or type of parameter is known as overloading.
Types Of
Overloading
1.Function
Overloading
2.Operator
Overloading
1. Function Overloading
The process of having two or more functions with the same name, but different parameters, is known as function overloading.
The
function is redefined by either using different types of arguments or a
different number of arguments. It is only through these differences that a
compiler can differentiate between functions.
Synatx:
return
type functionname(datatype variablename)
{
}
return
type functionname(datatype variablename, variablename)
{
}
return
type functionname(datatype variablename,datatype variablename)
{
}
Program:
#include<iostream.h>
#include<conio.h>
class
BCA
{
int
a,b;
public:
void
input()
{
cout<<”input
one number”;
cin>>a;
}
void
input(int x)
{
b=x;
}
void
show()
cout<<”a=”<<a;
cout<<”b=”<<b;
}
};
void
main()
{
BCA p;
p.input();
p.input(20);
p.show();
getch();
}
Output:
Input
one number 1
a=1
b=20
2.Operator overloading
Operator overloading is
a compile-time polymorphism in which the operator is overloaded to provide
special meaning to the user-defined data type. Operator overloading is used to overload
or redefine most of the operators available in C++. It is used to perform the
operation on the user-defined data type.
Syntax:
class classname
{
-----------
----------
Public:
return type operator++(argument)
{
---------
----------
}
returntype operator operatorname(argument)
{
-----------
-----------
}
};
Program:
#include<iostream.h>
#include<conio.h>
class
BCA
{
int n;
public:
BCA()
{
n=0;
void
operator++()
{
n=n-2;
}
void
operator—()
{
n=n+2;
}
void
show()
{
cout<<”n=”<<n;
}
};
void
main()
{
BCA a1;
a1.show();
++a1;
a1.show();
++a1;
a1.show();
--a1;
a1.show();
--a1;
a1.show();
getch();
}
Output:
n=0
n=-2 n=-4 n=-2 n=0
No comments:
Post a Comment