Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

c++
java
c #
ruby
polymorphism

What is polymorphism?

Educative Answers Team

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

Polymorphism is an object-oriented programming concept that refers to the ability of a variable, function, or object to take on multiple forms. In a programming language exhibiting polymorphism, class objects belonging to the same hierarchical tree (inherited from a common parent class) may have functions with the same name, but with different behaviors.

Example:

The classic example is of the Shape class and all the classes that are inherited from it, such as:

  • Rectangle

  • Triangle

  • Circle

svg viewer

Below is an example of Polymorphism:

class Shape
{
public:
Shape(){}
//defining a virtual function called Draw for shape class
virtual void Draw(){cout<<"Drawing a Shape"<<endl;}
};
class Rectangle: public Shape
{
public:
Rectangle(){}
//Draw function defined for Rectangle class
virtual void Draw(){cout<<"Drawing a Rectangle"<<endl;}
};
class Triangle: public Shape
{
public:
Triangle(){}
//Draw function defined for Triangle class
virtual void Draw(){cout<<"Drawing a Triangle"<<endl;}
};
class Circle: public Shape
{
public:
Circle(){}
//Draw function defined for Circle class
virtual void Draw(){cout<<"Drawing a Circle"<<endl;}
};
int main() {
Shape *s;
Triangle tri;
Rectangle rec;
Circle circ;
// store the address of Rectangle
s = &rec;
// call Rectangle Draw function
s->Draw();
// store the address of Triangle
s = &tri;
// call Traingle Draw function
s->Draw();
// store the address of Circle
s = &circ;
// call Circle Draw function
s->Draw();
return 0;
}

Explanation:

In the example above,

  • We used virtual keyword while defining the Draw() functions as a virtual function is a member function which when declared in the base class can be re-defined (Overriden) by the derived classes.

  • At run time the compiler looks at the contents of the pointer *s.

  • Since, the addresses of objects of tri, rec, and circ are stored in *s the respective Draw() function is called.

As you can see, each of the child classes has a separate implementation for the function Draw(). This is how polymorphism is generally used.

Types of polymorphism:

  • Compile time polymorphism

    • Example: Method overloading
  • Runtime polymorphism

    • Example: Method overriding