Purpose of run time Polymorphism in C++/CPP.

What is the main purpose of run time polymorphism? Why run time polymorphism is used in object oriented programming like C++? What is the main reason to use polymorphism in C++? Why late binding is used in C++?
These are the most frequently asked questions in interviews for C++ walkins or face to face interviews. If you are fresher then telling the definition alone is enough but by experienced professionals it is not acceptable. So what should be the answer?
If you are able to mention a real time scenario where it is used in proper manner then your work is done.
One such example is to create array of base class pointer which holds addresses of related derived class objects. I.e. Suppose an employee management system. Employee is base class and derived classes are employees like trainee, junior software engineer, senior. Software engineer, Lead engineer, manager etc.
Employee base class has virtual/pure virtual function like salaryIncrement, empPromotion.
Each derived class has its own implementation of these function. If management wants to use salaryIncrement then run time polymorphism allows to create array of base class pointers each having address of different derived class object and in a loop with same call syntax it can increment all employees salary at once without knowing the derived class object type at compile time.

C++ program to implement:Default constructor, One argument constructor, Copy constructor, overloaded assignment operator, destructor and overload + operator to concatenate two strings in a single program.

No comments:

Post a Comment