Вы находитесь на странице: 1из 2

What is polymorphism? Provide an example to explain it.

Polymorphism: Poly – Multiple and Morph - Form

Polymorphism means the ability to take more than one form. An operation may exhibit
different behavior in different instances. The behavior depends on the types of data used
in the operation. For example, consider addition operation. For two numbers, the
operation will generation sum. In case of two strings, it will generate a third string with
concatenation. Thus, polymorphism allows objects with different internal structure to
share same external interface. This means that a general class of operations can be
accessed in the same manner even though specific actions associated with each operation
may differ. There are two types of polymorphism:

Compile Time Polymorphism: Achieved using operator overloading and function


overloading

Run Time Polymorphism: Achieved using virtual functions.

Describe Abstract base class. Illustrate an example to explain it.

A pure virtual function is a function which does not have definition of its own. The
classes which derive from this class need to provide definition for such function. A class
containing at least one such pure virtual function is called as abstract base class. We can
not create objects of abstract class because it contains functions which have no definition.
We can create pointers and references to an abstract class.

Consider example of base class Shape and derived classes Circle, Rectangle, triangle etc.
The function Draw() is made pure virtual in the base class Shape. It is overridden by the
derived classes. So the class Shape becomes abstract base class.

class Shape
{
int x, y;
public:
virtual void draw() = 0;
};

class Circle: public Shape


{
public:
draw()
{
//Code for drawing a circle
}
};

class Rectangle: public Shape


{
Public:
void draw()
{
//Code for drawing a rectangle
}
};

class Triangle: public Shape


{
Public:
void draw()
{
//Code for drawing a triangle
}
};