3.2.4. Implications of Polymorphic Use of Classes
Q22. What is polymorphism? Explain the types of polymorphism.
Answer:
Polymorphism
Polymorphism is one of the important object oriented programming concept. It is a mechanism through which one operation or a function can take many forms depending upon the type of objects. Thus, a single operator.or function can be used in many ways.
Consider an example for adding two variables,
Types of Polymorphism
There are two types of polymorphism. They are,
(i) Compile Time Polymorphism
In compile time polymorphism, the most appropriate member function is called by comparing the type and the number of argument by the compiler at compile time. It is also known as early binding / static linking / static binding.
Example
(ii) Runtime Polymorphism
In this type of polymorphism, the most appropriate member function is called at runtime i.e., while the program is executing and the linking of function with a class occurs after compilation. Hence, it is called late binding or dynamic binding. It is implemented using virtual functions and the pointers to objects.
Example
Answer:
Polymorphism
Polymorphism is one of the important object oriented programming concept. It is a mechanism through which one operation or a function can take many forms depending upon the type of objects. Thus, a single operator.or function can be used in many ways.
Consider an example for adding two variables,
Sum = x+y
Here, x and y can be integer numbers
Sum = 2+5
or float numbers
Sum =2.5+7.5
The result of ‘Sum’ depends upon the values passed to it.Types of Polymorphism
There are two types of polymorphism. They are,
(i) Compile time polymorphism and
(ii) Runtime polymorphism.
(i) Compile Time Polymorphism
In compile time polymorphism, the most appropriate member function is called by comparing the type and the number of argument by the compiler at compile time. It is also known as early binding / static linking / static binding.
Example
#include<iostream.h>
#include<conio.h>
class Add
{
public:
void sum(int a, int b)
{
cout<<a+b;
}
void sum(int a, int b, int c)
{
cout<<a+b+c;
}
};
void main()
{
clrscr();
Add obj;
obj.sum(10, 20);
cout<<endl;
obj.sum(10, 20, 30);
}
OutputIn this type of polymorphism, the most appropriate member function is called at runtime i.e., while the program is executing and the linking of function with a class occurs after compilation. Hence, it is called late binding or dynamic binding. It is implemented using virtual functions and the pointers to objects.
Example
#include<iostream.h>
#include<conio.h>
class Baseclass
{
public:
virtual void show()
{
cout<<“Base class \n”;
}
};
class Derivedclass: public
Baseclass
{
public:
void show()
{
cout<<“\n Derived class \n”;
}
};
int main(void)
{
clrscr();
Baseclass *bp = new Derivedclass;
bp→show(); // RUN-TIME
POLYMORPHISM
getch();
return 0;
}
Output