π What is a Virtual Function?
A virtual function is a member function in the base class that you can override in a derived class.
It is declared using the keyword virtual
.
Virtual functions enable runtime polymorphism β meaning the function call is determined at runtime, not at compile time.
π§ Real-Life Analogy
Imagine youβre using a universal remote. If itβs programmed to control a TV today and an air conditioner tomorrow β its behavior changes at runtime, just like a virtual function call.
π§ Syntax of Virtual Function
class Base {
public:
virtual void show() {
// base class version
}
};
π§ͺ Example: Virtual Function in C++
#include <iostream>
using namespace std;
class Animal {
public:
virtual void sound() { // Virtual function
cout << "Animal makes a sound." << endl;
}
};
class Dog : public Animal {
public:
void sound() override { // Overriding virtual function
cout << "Dog barks." << endl;
}
};
int main() {
Animal* ptr;
Dog d;
ptr = &d;
ptr->sound(); // Calls Dog's sound() due to virtual function
return 0;
}
β Output:
Dog barks.
π― Key Concepts:
Term | Meaning |
---|---|
Virtual Function | Declared using virtual keyword in base class |
Overriding | Defining the same function in the derived class |
Polymorphism | Many forms β the correct function is chosen at runtime |
Base Class Pointer | Can point to derived class object |
β Why Use Virtual Functions?
- To achieve runtime polymorphism.
- To let derived classes customize behavior of functions.
- To allow base class pointers to call the derived class version of a function.
π Virtual Table (vtable) (Advanced Note)
Behind the scenes, C++ creates a virtual table (vtable) for each class with virtual functions.
At runtime, the program uses this table to decide which function to call, based on the actual object.
π Rules for Virtual Functions
- Must be declared with
virtual
in the base class. - Should be overridden in the derived class.
- A base class pointer/reference should be used to call the function.
- Canβt be static.
- Can be friend functions (but not virtual themselves).
- Destructors should also be virtual if the class is used polymorphically.
β What Happens Without virtual
?
If the base class function is not marked virtual
, the base class version is called β even if the object is of the derived class.
π§ͺ Example Without Virtual Function
class Animal {
public:
void sound() {
cout << "Animal sound" << endl;
}
};
class Cat : public Animal {
public:
void sound() {
cout << "Cat meows" << endl;
}
};
int main() {
Animal* ptr = new Cat();
ptr->sound(); // Output: Animal sound (early binding)
return 0;
}
π Summary Table
Feature | Description |
---|---|
Virtual Function | Allows function to be overridden dynamically |
Keyword | virtual |
Binding Type | Late Binding / Runtime Binding |
Achieves | Runtime Polymorphism |
Called By | Base class pointer or reference |