Polymorphism, in the context of object oriented programming, refer to the ability of objects to take on multiple forms. This is achieved through two main mechanism : Compile Time polymorphism and Run time polymorphism.
Compile-Time Polymorphism (Method Overloading):
How it work:
- Determined at Compile time.
- also known as Static Polymorphism.
- Implemented using function overloading and operator overloading.
class MathOperations
{
public:
int add(int a, int b)
{ return a+b; }
int add(double a, double b)
{ return a+b; }
};
int main()
{
MathOperations math;
int result1 = math.add(9+8);
int result2 = math.add(9.78,45.76);
return EXIT_SUCCESS;
}
How it is implemented:
- During compilation, the compiler resolves the function calls based on the provided arguments.
- The generated machine code instructions to call the appropriate function based on the types and number of arguments.
Run-Time Polymorphism (Method Overloading):
How it work
- Determined at runtime.
- Also known as dynamic polymorphism.
- Implemented using virtual functions and inheritance.
#include <iostream>
class Shape
{
public:
virtual void draw() const = 0; //pure function
};
class Circle: public Shape
{
public:
void draw const override()
{
std::cout<<"Drawing a Circle \n";
}
};
class Square:public Shape
{
public:
void draw const override()
{
std::cout<<"Drawing an Square \n";
}
};
int main()
{
Shape* shapes[] = {new Circle(), new Square()};
for(const Shape* shape : shapes)
{
shape->draw(); // runtime calls to functions
}
return EXIT_SUCCESS;
}
How it is implemented:
- Virtual functions are implemented using a mechanism call as virtual function table.
- The vtable is a table of function pointers associated, with each class that has virtual functions.
- When a class has a virtual function, the compiler adds a pointer to the vtable in the object memory layout.
- The vtable contains pointers to the actual implementations of the virtual functions in the class or tis subclass.
- During runtime, the correct function is called based on the dynamic type of the object.
Key points
- For a every class there is only one vtable.
- For a every object there is only one vptr.
- so if there are 10 object of class A then there is 1 vtable and 10 vptr pointers.
- Lets say there is class A (having two function draw() and Fun() ) and class B is child of A, and overload only virtual function draw(), then below is the representation.
Top comments (0)