Free tutorials & notes in Hindi & English · Clean code examples · Mobile friendly learning
📘 Lesson  ·  Lesson 71

Virtual Functions

Written and reviewed by · Senior IT Faculty · 15+ years’ experience

Quick recap

A virtual function lets a call through a base pointer run the derived version at run time. This page is a compact syntax reference; for how it works internally (the vtable), virtual destructors, and the full concept, see the main virtual functions lesson and polymorphism.

Basic syntax

C++
class Base {
public:
    virtual void draw();      // 'virtual' in the base
};
class Derived : public Base {
public:
    void draw() override;     // 'override' in the derived
};

Base-pointer example

C++
#include <iostream>
using namespace std;
class Animal { public: virtual void speak() { cout << "...\n"; } };
class Dog : public Animal { public: void speak() override { cout << "Woof\n"; } };
class Cat : public Animal { public: void speak() override { cout << "Meow\n"; } };

int main() {
    Animal *arr[2] = { new Dog(), new Cat() };
    for (Animal *a : arr) a->speak();   // run-time dispatch
}
Output:
Woof
Meow

With vs without virtual

With virtualWithout virtual
basePtr->f() runsDerived's versionBase's version
DispatchRun time (dynamic)Compile time (static)

Pure virtual syntax

Add = 0 to make a function pure virtual — no body, and derived classes must implement it. This makes the base an abstract class:

C++
class Shape {
public:
    virtual double area() = 0;   // pure virtual
};

See abstract classes for the full story.

Keyword cheat sheet

KeywordWhereMeaning
virtualBase functionCan be overridden; enables dynamic dispatch
overrideDerived functionVerifies it overrides a base virtual
= 0Base functionPure virtual; class becomes abstract
finalFunction/classPrevents further overriding/derivation

Common mistakes

  • Writing = 0 but still giving the function a body without meaning to.
  • Expecting dispatch when calling on an object instead of a pointer/reference.
  • A mismatched signature silently hiding instead of overriding (use override).
  • Forgetting a virtual destructor in the base (covered in the main lesson).
🏋️ Practice

Write a base Employee with a virtual salary(), and derived Manager and Intern. Put pointers in an array and print each salary through the base pointer.

Summary

  • virtual goes on the base function; override on the derived.
  • Call through a base pointer/reference for run-time dispatch.
  • = 0 makes a pure virtual and an abstract class.
  • Keyword cheat sheet: virtual, override, =0, final.
  • For internals and design, see the main virtual functions lesson.

Frequently Asked Questions

What is the syntax of a virtual function in C++?
You declare a virtual function by writing virtual before the return type in the base class, such as virtual void draw();. In a derived class you redefine it and add override, like void draw() override;, to have the compiler check the override.
What is a pure virtual function in C++?
A pure virtual function has no body in the base class and is declared by assigning = 0, such as virtual void draw() = 0;. It forces derived classes to provide their own implementation and makes the base class an abstract class that cannot be instantiated.
Do you write virtual on the overriding function in C++?
You do not need to repeat virtual in the derived class; once a function is virtual in the base, its overrides are automatically virtual too. It is good practice to add override instead, which documents intent and lets the compiler catch signature mismatches.
How do you call a virtual function in C++?
You call it like any member function, but for polymorphic behaviour you invoke it through a base-class pointer or reference, such as basePtr->draw();. The version matching the actual object is then selected at run time.
What is the difference between virtual and override in C++?
virtual in the base class marks a function as overridable and enables run-time dispatch. override in a derived class states that the function is intended to override a base virtual, letting the compiler verify the signature and report an error if it does not match.

त्वरित सार

Virtual function base pointer के ज़रिए call को run time पर derived version चलाने देता है। यह पृष्ठ एक संक्षिप्त syntax reference है; यह आंतरिक रूप से कैसे काम करता है (vtable), virtual destructors, और पूरे concept के लिए, मुख्य virtual functions lesson और polymorphism देखें।

बुनियादी syntax

C++
class Base {
public:
    virtual void draw();      // base me 'virtual'
};
class Derived : public Base {
public:
    void draw() override;     // derived me 'override'
};

Base-pointer उदाहरण

C++
#include <iostream>
using namespace std;
class Animal { public: virtual void speak() { cout << "...\n"; } };
class Dog : public Animal { public: void speak() override { cout << "Woof\n"; } };
class Cat : public Animal { public: void speak() override { cout << "Meow\n"; } };

int main() {
    Animal *arr[2] = { new Dog(), new Cat() };
    for (Animal *a : arr) a->speak();   // run-time dispatch
}
Output:
Woof
Meow

virtual के साथ बनाम बिना

virtual के साथvirtual के बिना
basePtr->f() चलाता हैDerived का versionBase का version
DispatchRun time (dynamic)Compile time (static)

Pure virtual syntax

किसी function को pure virtual बनाने को = 0 जोड़ें — कोई body नहीं, और derived classes को इसे implement करना होगा। यह base को abstract class बनाता है:

C++
class Shape {
public:
    virtual double area() = 0;   // pure virtual
};

पूरी कहानी के लिए abstract classes देखें।

Keyword cheat sheet

Keywordकहाँअर्थ
virtualBase functionOverride हो सकता; dynamic dispatch सक्षम
overrideDerived functionसत्यापित करता कि यह base virtual override करता है
= 0Base functionPure virtual; class abstract बनती है
finalFunction/classआगे override/derivation रोकता है

आम गलतियाँ

  • = 0 लिखना पर बिना इरादे function को body भी देना।
  • Pointer/reference के बजाय object पर call करते समय dispatch की उम्मीद।
  • बेमेल signature चुपचाप override के बजाय hiding करना (override इस्तेमाल करें)।
  • Base में virtual destructor भूलना (मुख्य lesson में शामिल)।
🏋️ अभ्यास

एक base Employee लिखें जिसमें virtual salary() हो, और derived Manager तथा Intern। Pointers एक array में रखें और हर salary base pointer के ज़रिए print करें।

सारांश

  • virtual base function पर जाता है; override derived पर।
  • Run-time dispatch के लिए base pointer/reference के ज़रिए call करें।
  • = 0 pure virtual और abstract class बनाता है।
  • Keyword cheat sheet: virtual, override, =0, final।
  • Internals और design के लिए, मुख्य virtual functions lesson देखें।
← 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.