Skip to main content

Need of virtual function

Short answer

Virtual functions allow a base class pointer to call the derived class's overridden function at run time, enabling polymorphism. Without virtual, the base version is called even when the object is derived. Example: virtual void show() in base ensures p->show() executes the derived's version.

Why do we need virtual function? Explain with suitable example.

A virtual function is a member function declared with the keyword virtual in the base class and redefined in derived classes. It makes the compiler choose the function version at run time based on the type of the object pointed to, not on the type of the pointer.

Why we need it

When a base class pointer holds the address of a derived class object, a normal (non-virtual) function call is bound at compile time to the base version, because the pointer is of the base type. The derived version never runs, which is wrong when we want derived behaviour. Declaring the function virtual fixes this and gives run-time polymorphism (late binding). It lets us:

  • write one piece of code that works with all classes in a hierarchy (e.g. an array of Shape* holding circles and rectangles);
  • add new derived classes without changing the code that uses the base pointer.

Example without virtual

#include <iostream>
using namespace std;

class Base {
public:
    void show() { cout << "Base show" << endl; }
};
class Derived : public Base {
public:
    void show() { cout << "Derived show" << endl; }
};

int main() {
    Base *p;
    Derived d;
    p = &d;
    p->show();       // prints "Base show" - not wanted
    return 0;
}

Example with virtual

#include <iostream>
using namespace std;

class Base {
public:
    virtual void show() { cout << "Base show" << endl; }
};
class Derived : public Base {
public:
    void show() { cout << "Derived show" << endl; }
};

int main() {
    Base *p;
    Derived d;
    p = &d;
    p->show();       // prints "Derived show"
    return 0;
}

Output: Derived show

With virtual, the call p->show() uses the actual object (Derived) to pick the function through the vtable.

✓ Answer checked by Claude Opus 5.5 (high effort)

All Object Oriented Programming chapter 7 questions →