Skip to content

Virtual Functions

πŸ“˜ 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:

TermMeaning
Virtual FunctionDeclared using virtual keyword in base class
OverridingDefining the same function in the derived class
PolymorphismMany forms β€” the correct function is chosen at runtime
Base Class PointerCan point to derived class object

βœ… Why Use Virtual Functions?

  1. To achieve runtime polymorphism.
  2. To let derived classes customize behavior of functions.
  3. 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

  1. Must be declared with virtual in the base class.
  2. Should be overridden in the derived class.
  3. A base class pointer/reference should be used to call the function.
  4. Can’t be static.
  5. Can be friend functions (but not virtual themselves).
  6. 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

FeatureDescription
Virtual FunctionAllows function to be overridden dynamically
Keywordvirtual
Binding TypeLate Binding / Runtime Binding
AchievesRuntime Polymorphism
Called ByBase class pointer or reference