C++ 45: Polymorphism
- Polymorphism indicates the similar behavior of objects of different classes.
- The polymorphism can be achieved only for those classes whose behavior is same and whose base class is same.
- By using the technique we can develop a block of code which will work for different objects of the classes whose behavior is same. Such code is called as polymorphic code and process to develop such code is called as polymorphism.
- Polymorphism is actually a Greek word. In Greek poly means many and Morph means forms.
- Polymorphism is categorized into following two types:
- 1) Compile time Polymorphism
- 2) Runtime Polymorphism
Compile Time Polymorphism
- In Compile time polymorphism compiler decides the function call at compile time (i.e. before program begins its execution) as per type of pointer
- The compile time polymorphism is also called as early binding , Static Linking or static binding.
- C++ by default performs Compile time polymorphism.
- The operator overloading, function oerloading , function overriding are some of the examples of compile time polymorphism.
Run time polymorphism
- In run time polymorphism compiler decides the function call during the execution of program(i.e. at runtime)as per the type of object s created and not as per the type of pointer.
- The runtime polymorphism is also called as Late binding, Dynamic linking or Dynamic Binding.
Important:
- C++ by default performs Compile time polymorphism.
- If we want to achieve runtime polymorphism, C++ provides us a special feature and the concept of virtual functions.
"By using base class pointer it is possible to create an object of derived class dynamically". But by using base class pointer we can call only the inherited and override functions for the derived class object. That means by using base class pointer it is not possible to call the newly defined functions in derived class.
Example:
Creating Derived class Object Using Base class Pointer(Compile time poly.)
#include <iostream>using namespace std;
class Base{public: void fun1() { cout << "Base class Function 1" << endl; } void fun2() { cout << "Base class Function 2" << endl; }};class Derived : public Base{public: //Function Overriding void fun1() { cout << "Derived class Function 1" << endl; } void fun2() { cout << "Derived class Function 2" << endl; } void func3() { cout << "Derived class Function 3" << endl; }};
int main(){ Base *p = new Derived(); p->fun1(); //Perform compile ime polymorphism and calles base class fuction as pointer is of base class p->fun2(); //We cannot call newly defined functions in derived class //p->fun3(); return 0;
}Output:
Base class Function 1
Base class Function 2
Comments
Post a Comment