Run-time polymorphism
Run-time
polymorphism means the method call is resolved at run time, not at compile
time.
Use
- Base class pointer
- Points to the derived class
object
- Calls the virtual function
Key Concepts
1
Inheritance
Run-time
polymorphism works only with inheritance.
class Base
{ };
class
Derived : public Base { };
2
Virtual Function
A virtual
function is a member function of a class that is declared using the keyword
virtual and is overridden in a derived class.
virtual
void show();
3 Base
Class Pointer
A base
class pointer can point to a derived class object.
Base *b;
b = new
Derived();
Need Run-Time Polymorphism
- To achieve dynamic behavior
- To support flexibility and
extensibility
- Used heavily in:
- GUI systems
- Game engines
- Operating systems
- Real-world modeling
Process of Run-Time Polymorphism (Internally
)
Virtual
Table (V-Table)
- Compiler creates a V-Table
- V-Table stores addresses of
virtual functions
- Each object contains a V-Pointer
(VPTR)
At
runtime, correct function is selected using VPTR.
Rules of Run-Time Polymorphism
- Must use inheritance
- Function must be virtual
- Function call must be through a base
class pointer
- Function overriding must have the same
signature
- Happens at run time
Example
: Using Virtual Function
#include
<iostream>
using
namespace std;
class Base
{
public:
virtual void show() {
cout << "This is Base class
show function" << endl;
}
};
class
Derived : public Base {
public:
void show() {
cout << "This is Derived
class show function" << endl;
}
};
int main()
{
Base *b;
Derived d;
b = &d;
b->show();
return 0;
}
Output
This is a derived class showing a function
Difference: Compile-time vs Run-time
Polymorphism
|
Feature |
Compile-time |
Run-time |
|
Binding |
Early |
Late |
|
Speed |
Faster |
Slightly slower |
|
Example |
Overloading |
Virtual functions |
|
Flexibility |
Less |
More |
==============================================================
0 Comments