Runtime / Dynamic Polymorphism
Means Same named functions in Base & derv class & both to be accessed
using Base class Pointer only.
Achieved using Virtual Function
Virtual function
Function prefixed with virtual keyword in base class.
It allows the correct function to be selected at runtime based on the
actual object type, not just the pointer or reference type.
How vtable Works?
#include <iostream>
class Base {
public:
virtual void A() {cout << "Base\n";}
};
class Derv : public Base {
public:
void A() override {cout << "Derv\n";}
};
int main() {
Base* a = new Derv();
a->A(); //////////// Derv::A() called runtime
delete a;
}
Virtual constructor?
There is no such thing as a virtual constructor in C++.
Constructors are not inherited and cannot be virtual.
Why? Because the object does not exist yet when the constructor runs.
The type must already be known so that memory can be allocated and the
object initialized. Dynamic dispatch works only after an object exists.
Virtual destructor?
A destructor declared as
virtual in the base class.
if Base class destructor is not virtual, it will not be called
if some deletion is present in base class that will not be deleted
| Base Destructor not called | Base Destructor called Due to virtual |
|---|---|
|
|