What is polymorphism? Explain with an example.

Showing Answers 1 - 2 of 2 Answers

samiksc

  • Jan 25th, 2006
 

Polymorphism is the ability to assume many forms. In short it refers to several methods / operators sharing the same name but having different parameter list and different implementations. Variables also can be polymorphic. There are two ways polymorphism can be achieved:

  • Polymorphism through scope: For example, variables polymorphism.

void F()

{

int cnt = 100;

string userResponse;

cin >> userResponse;

if (userResponse == 'y')

{

int cnt = 50;

cout << cnt << "\n";

}

cout << cnt << "\n"

}

If a class declares two functions having same name but different parameters it is also polymorphism (in the same scope).

  • Polymorphism through inheritance:
    • Overloading: Say class Shape has a function CalcArea(int, int). Say a class Circle() is derived from Shape. It overloads the CalcArea() method by specifying only one int parameter, radius.
    • Overriding: Continuing the same example suppose a class rectangle is derived from Shape. It overrides the method CalcArea(int, int) to provide its implementation. Class Triangle also overrides the method and provides its implementation.
    • A derived class declares a data member having same name as the base class data member.

  Was this answer useful?  Yes

ambeer

  • Sep 5th, 2010
 

Polymorphism means takes more than one form. Means one function or operator can have same name but differnet parameters and different implementations. There are two types of polymorphism.

1. Static polymorphism
2. Dynamic polymorphism.

Static polymorphism: It is also known as Early binding. Means binding/polymorphism takes place at the complie time. Eg: method overloading and operator overloading

Dynamic ploymorphism: It is also know as Late binding. Means binding/polymorphism takes place at the rum time: Eg: virtual functions and abstract classes

  Was this answer useful?  Yes

Give your answer:

If you think the above answer is not correct, Please select a reason and add your answer below.

 

Related Answered Questions

 

Related Open Questions