C++ – Polymorphism

Polymorphism is the ability of an object to exhibit multiple behaviors. C++ allows two types of polymorphism, Static and Dynamic. Static polymorphism happens at compile time via function overloading whereas Dynamic polymorphism is exhibited at run time via function overriding.

In static polymorphism, a function is overloaded either by changing the type or count of its parameters. Please not that altering the return type of a function does not make it polymorphic. All of the functions listed below are polymorphs of each other.

  void demoFunction()
  void demoFunction(int)
  void demoFunction(float)
  void demoFunction(float,int)

Dynamic polymorphism in C++ is enabled via Inheritance.  A method declared in the base class can be overridden in the derived class. For example,

class Base {
public:
	void testFunction(){
		std::cout << "Inside Base" << std::endl;
	}
};

class Derived :public Base {
public:
	void testFunction() {
		std::cout << "Inside Derived" < testFunction();
    return 0;
}

Output:

Inside Derived

In C++, it is possible to make a base class pointer point to an object of the derived class. But if we have run time polymorphism enabled via method overriding, this might lead to something known as static binding when we try to call an overridden method. For example,

class Base {
public:
	void testFunction(){
		std::cout << "Inside Base" << std::endl;
	}
};

class Derived :public Base {
public:
	void testFunction() {
		std::cout << "Inside Derived" < testFunction();
    return 0;
}

Output:

Inside Base

As we can see, we ended up calling the testFunction() method of the base class although we had created an object of the derived class type. In order to avoid this, we need to make the base class method as virtual. You can read more about Virtual Functions here.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s