Polymorphism (C++)

Polymorphism is a language mechanism that permits the same interface to invoke different functions or operators depending upon the type of objects using the interface.

Polymorphism is a property by which we can send the same message to objects of several different classes, and each object can respond in a different way depending on its class. We can send such a message without knowing to which of the classes the objects belongs.

In C++, polymorphism is implemented by means of virtual functions and dynamic binding. The keyword "Virtual" is used to perform the polymorphism concept in C++. In other words, polymorphism means "to carry out different processing steps by functions having same message". It treats objects of related classes in a generic manner.

When a polymorphic function invokes a member function using a base class reference or pointer, dynamic binding executes the code from the derived class even though the polymorphic function may be unaware that the derived class exists. The code that is executed depends on the type of the object rather than on the type of the reference or pointer. In this way, objects of a derived class can be substituted for objects of a base class without requiring any changes in the polymorphic functions that use the objects.

Polymorphism is of two types. They are:

i. Compile Time Polymorphism: This is implemented using function overloading and operator overloading.

ii. Runtime Polymorphism: This is implemented using virtual function.

Function overloading is realized by invoking a suitable function whose signature matches with the arguments specified in the function call statement. Operator overloading is realized by allowing operators to operate on the user defined data-types with the same interface as that of the standard data types. In both cases, the compiler is aware of the complete information regarding the type and number of operands. Hence, it is possible for the compiler to select a suitable function at the compile-time.

It's very calm over here, why not leave a comment?

Leave a Reply

You must be logged in to post a comment.