*/
Stuck? Need help? Ask questions on our forums.

Other Views

corner
*/

CPLUSPLUS FAQ - Why Polymorphism is So Important

Why Polymorphism is so important? What is it’s role in OO programming?

Polymorphism gives us the ultimate flexibility in extensibility which is a basis of OO programming. Understanding Polymorphism is crucial to any OO language professional , be it a Java , C++ or C# programmer.

Going back to our example of Vehicle and its descendents – say in our solution we created a Base class Vehicle with three Derived types; Car, Truck and a Bike. All have a function called GetRegistration(). Now this functions, although has the same name in all classes, could perform slightly different types of calculations for each Class. There comes a scenario where we need to add a new Type of Vehicle- Bus to our Class Hierarchy.

We want to be able to ‘plug-in’ this class into our application without having to make any code changes in the original code and call the GetRegistration() of Bus class during run time. A concept of ‘late binding’ is used in C++ to determine the corresponding function to be called for the respective derived class during runtime. This gives derived classes the ability to behave in their typical manners, thus exhibiting Polymorphism or different forms. Attaching the keyword ‘Virtual’ to a method in the Base classes gives the derived classes the power of polymorphic behavior.

class Vehicle
{
public:
	Vehicle(){}
	Virtual void GetRegistration();
};
class Car : public Vehicle
{
public:
	Car(){}
	void GetRegistration()
        	{
             	       cout << "Car, registration: ";  
        	}
};
class Truck : public Vehicle
{
public:
	Truck(){}
	void GetRegistration()
        	{
             	        cout << "Truck, registration: ";   
        	}
};
Vehicle* vp1 = new Car();
Vehicle* vp2 = new Truck();
vp1->GetRegistration();	// calls GetRegistration() of Car	
vp2->GetRegistration();	// calls GetRegistration() of Truck	


C++ FAQ Home
corner
© 1996-2008 CommunityHeaven LLC. All rights reserved. Reproduction in whole or in part, in any form or medium without express written permission is prohibited.
Violators of this policy may be subject to legal action. Please read our Terms Of Use and Privacy Statement for more information.
North American business development: Nicolai Wadstrom. Publisher: Lars Hagelin.