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.
The function call is resolved at runtime based on the type of object,
not the pointer.
Need for Virtual Function
- Function calls are decided at runtime
- This is called Late Binding
(Dynamic Binding)
Syntax of Virtual Function
class Base
{
public:
virtual void show() {
cout << "This is Base class
show function";
}
};
- virtual keyword is written in the base
class
- Derived class overrides the
function
Rules of Virtual Function
- Declared using the virtual keyword
- Must be a member function
- Cannot be static
- Call is resolved at runtime
- A function call is made using a base
class pointer
- Virtual function remains
virtual in derived classes
Example
– With Virtual Function
Program
#include
<iostream>
using
namespace std;
class Base
{
public:
virtual void show() {
cout << "Base class show
function" << endl;
}
};
class
Derived : public Base {
public:
void show() {
cout << "Derived class show
function" << endl;
}
};
int main()
{
Base* b;
Derived d;
b = &d;
b->show();
return 0;
}
Output
Derived
class show function
Process of Virtual Function Works
Virtual
Table (V-Table) Concept
- The compiler creates a V-Table
for each class
- V-Table stores addresses of
virtual functions
- Each object has a V-Pointer
pointing to its V-Table
- At runtime, the function address
is fetched from the V-Table
Pure Virtual Function
A function
with no definition in the base class.
virtual
void display() = 0;
- Makes class Abstract Class
- The derived class must override
the function
Example
class
Animal {
public:
virtual void sound() = 0;
};
class Dog
: public Animal {
public:
void sound() {
cout << "Dog barks"
<< endl;
}
};
Difference: Virtual Function vs
Non-Virtual Function
|
Feature |
Virtual Function |
Non-Virtual Function |
|
Binding |
Runtime |
Compile Time |
|
Polymorphism |
Yes |
No |
|
Keyword |
virtual |
No keyword |
|
Flexibility |
High |
Low |
===================================================
0 Comments