Free tutorials & notes in Hindi & English · Clean code examples 🧰 Free PDF & Image Tools →
🟣 OOP  ·  Lesson 48

Virtual Functions in C++

In this lesson: How virtual functions work in C++, override keyword, vtable and virtual destructors — with output. In Hindi & English.

What is a virtual function?

A virtual function is a member function marked virtual in a base class, designed to be overridden by derived classes. Its point is dynamic dispatch: when you call it through a base-class pointer or reference, C++ runs the version belonging to the actual object, not the pointer's type.

The problem it solves

Without virtual, a call through a base pointer always runs the base version, ignoring the override. Compare:

C++
class Base { public: virtual void hi() { cout << "Base\n"; } };
class Derived : public Base { public: void hi() override { cout << "Derived\n"; } };

int main() {
    Base *p = new Derived();
    p->hi();          // "Derived" — thanks to virtual
    delete p;
}
Output:
Derived

Remove virtual and this would print Base instead.

The override keyword

Add override to a derived function you intend as an override. If it does not actually match a base virtual, the compiler stops you — catching typos in the signature:

C++
class Shape { public: virtual double area() { return 0; } };
class Circle : public Shape {
    double r;
public:
    Circle(double x) : r(x) {}
    double area() override { return 3.14159 * r * r; }  // safe
};

How it works: the vtable

Most compilers implement this with a vtable — a per-class table of function pointers. Each polymorphic object holds a hidden pointer to its class's vtable, and a virtual call looks up the right function there at run time. This is why virtual calls have a tiny overhead over ordinary calls.

Virtual destructors

If you delete a derived object through a base pointer, the destructor must be virtual — otherwise only the base part is destroyed and the derived resources leak:

C++
class Base {
public:
    virtual ~Base() { cout << "~Base\n"; }   // virtual destructor
};
class Derived : public Base {
public:
    ~Derived() { cout << "~Derived\n"; }
};
// delete (Base*)new Derived();  → ~Derived then ~Base
💡 Rule

Any class with a virtual function should also have a virtual destructor.

Overriding vs hiding

True overriding needs a matching signature on a virtual base function. If the base function is not virtual, or the signatures differ, the derived function merely hides the base one — no dynamic dispatch. The override keyword guards against this by mistake.

Common mistakes

  • Forgetting virtual, so overrides are ignored through base pointers.
  • Omitting a virtual destructor in a polymorphic base (resource leak).
  • A slightly different signature causing hiding instead of overriding (use override).
  • Expecting dynamic dispatch when calling on an object rather than a pointer/reference.

For a compact syntax reference and quick example, see the virtual functions syntax page. For the wider idea, see polymorphism.

🏋️ Practice

Build a Shape base with a virtual area() and a virtual destructor. Derive Circle and Rectangle. Store them via Shape* pointers and print each area through the base pointer.

Summary

  • A virtual function enables run-time dispatch to the right override.
  • Call it through a base pointer/reference for polymorphism.
  • override makes the compiler verify your override.
  • Compilers use a vtable to resolve virtual calls at run time.
  • Always give a polymorphic base class a virtual destructor.

Frequently Asked Questions

What is a virtual function in C++?
A virtual function is a member function declared with the virtual keyword in a base class, meant to be overridden in derived classes. When called through a base-class pointer or reference, the version matching the actual object is chosen at run time, enabling run-time polymorphism.
What does the override keyword do in C++?
The override keyword tells the compiler that a function is meant to override a virtual function from the base class. If the signature does not actually match a base virtual function, the compiler reports an error, which catches subtle mistakes early.
How do virtual functions work internally in C++?
Most compilers implement virtual functions using a vtable — a table of function pointers per class. Each object of a polymorphic class holds a hidden pointer to its class's vtable, and a virtual call looks up the correct function through that table at run time.
Why do you need a virtual destructor in C++?
When you delete a derived object through a base-class pointer, the destructor must be virtual so the derived destructor runs too. Without a virtual destructor only the base part is destroyed, leaking the derived class's resources, so polymorphic base classes should always have one.
What is the difference between overriding and function hiding in C++?
Overriding replaces a base virtual function with a matching derived one, chosen at run time. Function hiding happens when a derived class declares a function with the same name but the base version is not virtual or the signature differs, so the base version is simply hidden rather than polymorphically overridden.
← Back to C++ Tutorial
🔗

Share this topic with a friend

यह topic किसी दोस्त को भेजें

Found it useful? Send it to a classmate learning the same thing.

अच्छा लगा? जो दोस्त यही सीख रहा है, उसे भेज दीजिए।

💻 Live Code Editor

This page's programs are ready here — run them, edit them, and learn. No installation needed.
Powered by OneCompiler. The code loads into the editor automatically — press Run to see the output. If the editor does not open, open it in a new tab.
Next topicAbstract Classes and Pure Virtual Functions Your progress: 48 / 81 (59%) · Lesson 49 / 81 Continue →

How was this lesson?

Your feedback helps us make the content better.

Write a review or suggestion (optional)

After approval, your name and city may appear publicly with your review. Please do not write your email or phone number.

▶ CodingEasily on YouTube

Learn with video lessons in easy Hindi

Featured video: RDBMS Part 3 – Class XI Commerce IT

▶ Subscribe – it’s free