Skip to main content

Member function overriding with virtual function

Short answer

Overiding a virtual function enables run-time polymorphism, so a base pointer/reference calls the derived version depending on the actual object type. This allows a uniform interface to handle different behaviors, adding new derived classes without modifying existing code.

Explain the reason for member function over-riding when using virtual function.

Overriding means a derived class redefines a base class member function with the same name, return type and parameters. When the base function is declared virtual, the version to run is chosen by the type of the object, not by the type of the pointer or reference.

Why overriding is needed

  • A derived class often needs behaviour different from the base class (a Circle computes area differently from a Rectangle).
  • Without virtual, a base pointer always calls the base version (static binding), so the derived behaviour is ignored.
  • With virtual, the compiler creates a vtable; the call through a base pointer goes to the overriding function of the actual object at run time (dynamic binding).
  • It lets one interface (base->show()) work for many different object types, so new derived classes can be added without changing the calling code.

Example

#include <iostream>
using namespace std;

class Base {
public:
    virtual void show() { cout << "Base show\n"; }
    void display()      { cout << "Base display\n"; }  // not virtual
};
class Derived : public Base {
public:
    void show()    { cout << "Derived show\n"; }       // overrides
    void display() { cout << "Derived display\n"; }    // only hides
};

int main() {
    Derived d;
    Base *p = &d;
    p->show();      // Derived show   (virtual, run-time binding)
    p->display();   // Base display   (compile-time binding)
    return 0;
}

The result shows that only the virtual function is overridden and resolved at run time; the non-virtual one is bound by the pointer type.

✓ Answer checked by Claude Opus 5.5 (high effort)

All Object Oriented Programming chapter 7 questions →