Compile Time
Polymorphism
In C++
This
type of polymorphism is achieved by function overloading or operator
overloading.
· Function Overloading
· Operator Overloading
Fig:Compile Time Polymorphism In C++ |
1.
Function Overloading
When there are multiple functions with same name but
different parameters then these functions are said to be overloaded. Functions can be overloaded by change in number of arguments or/and change in type of arguments.
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.Operating System:
C++ also provide
option to overload operators. For example, we can make the operator (‘+’) for
string class to concatenate two strings. We know that this is the addition
operator whose task is to add two operands.
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