What are Virtual Functions in C++?
Learn what virtual functions in C++ are, how the vtable enables runtime polymorphism, why virtual destructors matter, and see clear code examples.
Expected Interview Answer
A virtual function is a member function declared with the virtual keyword in a base class so that when it is called through a base-class pointer or reference, the version defined in the actual derived object runs instead of the base version.
Virtual functions enable runtime (dynamic) polymorphism. The compiler gives each polymorphic class a hidden table of function pointers called the vtable, and each object stores a hidden vptr that points to its class's vtable. When a virtual call is made through a base pointer, the program looks up the correct override in the vtable at run time rather than binding the call at compile time. Declaring the base destructor virtual is essential so that deleting a derived object through a base pointer runs the full destructor chain.
- Enables runtime polymorphism through base pointers and references
- Lets you extend behavior in derived classes without changing calling code
- Supports the open/closed principle and plugin-style designs
- A virtual destructor prevents resource leaks when deleting via a base pointer
- Allows collections of heterogeneous objects handled through one interface
AI Mentor Explanation
A captain signals 'next bowler, bowl your specialty' without naming the delivery. A spinner responds with a googly, a pacer with a yorker — the same instruction resolves to a different action depending on who actually holds the ball, exactly as a virtual call resolves to the real object's override at run time.
Step-by-Step Explanation
Step 1
Declare virtual in the base
Mark the base-class member function with the virtual keyword so it participates in dynamic dispatch.
Step 2
Override in derived classes
Provide the same signature in each derived class and use the override specifier to catch mismatches at compile time.
Step 3
Use a base pointer or reference
Store or pass derived objects through a base-class pointer or reference so the actual type is only known at run time.
Step 4
Call through the base type
Invoke the virtual function; the vptr and vtable route the call to the correct derived override.
Step 5
Make the destructor virtual
Declare the base destructor virtual so deleting a derived object via a base pointer runs the full destructor chain.
What Interviewer Expects
- A clear definition tying virtual functions to runtime polymorphism
- Understanding of vtable and vptr mechanics
- Knowing why base destructors must be virtual
- Difference between compile-time and run-time binding
- Correct use of override and the cost of virtual dispatch
Common Mistakes
- Forgetting to declare the base destructor virtual, causing resource leaks
- Thinking a function is virtual in derived classes only if re-marked virtual (it stays virtual automatically)
- Confusing overloading with overriding
- Calling virtual functions from a constructor or destructor and expecting dynamic dispatch
- Believing virtual dispatch works through object slicing by value
Best Answer (HR Friendly)
“A virtual function lets a program pick the right version of a behavior based on the real object it is working with, not the general type it was written against. It is how C++ lets one piece of code work correctly with many related object types.”
Code Example
#include <iostream>
#include <memory>
class Shape {
public:
virtual double area() const { return 0.0; }
virtual ~Shape() = default; // virtual destructor is essential
};
class Circle : public Shape {
double r;
public:
explicit Circle(double radius) : r(radius) {}
double area() const override { return 3.14159 * r * r; }
};
class Square : public Shape {
double s;
public:
explicit Square(double side) : s(side) {}
double area() const override { return s * s; }
};
int main() {
std::unique_ptr<Shape> shapes[] = {
std::make_unique<Circle>(2.0),
std::make_unique<Square>(3.0)
};
for (const auto& shape : shapes)
std::cout << shape->area() << '\n'; // resolves at run time
}Follow-up Questions
- How does the vtable and vptr mechanism implement virtual dispatch?
- Why must a base class destructor be virtual?
- What is a pure virtual function and an abstract class?
- What is object slicing and how does it defeat virtual dispatch?
- What is the runtime cost of a virtual function call?
MCQ Practice
1. What does the virtual keyword enable in C++?
virtual makes the call resolve at run time to the actual object's override rather than the static base type.
2. Why should a base class with virtual functions declare a virtual destructor?
Without a virtual destructor, deleting a derived object through a base pointer is undefined and can leak resources.
3. A pure virtual function is declared with which syntax?
The = 0 specifier makes the function pure virtual, turning the class into an abstract base class.
Flash Cards
What is a virtual function? — A base-class member function that dispatches to the derived override at run time when called through a base pointer or reference.
What data structures implement virtual dispatch? — A per-class vtable of function pointers and a per-object vptr pointing to that vtable.
Why make a base destructor virtual? — So that deleting a derived object through a base pointer destroys the full object and releases its resources.
Pure virtual function syntax? — virtual returnType name(args) = 0; it makes the class abstract and cannot be instantiated.