Lesson 28 +40 XP

Function Overriding, Virtual Functions & Run-Time Polymorphism

Function Overriding, Virtual Functions & Run-Time Polymorphism

A derived class can override a base-class function by defining its own version with the same signature. Which version runs, though, depends on how the function is called.

Through a base-class pointer, C++ normally calls the base version, chosen at compile time. Declaring the function virtual makes C++ choose at run time, according to the actual object.

This is run-time polymorphism, the most important idea of Unit III.

1. Function Overriding

Function overriding means redefining, in a derived class, a member function of the base class with the same name, same parameter list and same return type. The derived version hides the base version for objects of the derived class.

C++
#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;
    } // overrides Base::show
};

int main() {
    Derived d;
    d.show();       // Derived's version
    d.Base::show(); // the base version is still reachable with ::
    return 0;
}

Output:

OUTPUT
Derived show
Base show

Overloading vs overriding

Function overloadingFunction overriding
same name, different parameter listssame name, same signature
functions are in the same scope (same class or namespace)functions are in a base and a derived class
inheritance not neededinheritance needed
resolved at compile timeresolved at run time if the function is virtual
compile-time polymorphismrun-time polymorphism (with virtual)
return type alone cannot differreturn type must be the same (or a covariant pointer/reference)

2. Pointers to Derived Classes

A base-class pointer can point to an object of any class publicly derived from it. This is safe, because a derived object contains a complete base-class part.

C++
Base* bptr;
Derived d;
bptr = &d; // allowed: a Derived IS-A Base

The reverse, a derived-class pointer to a base object, is not allowed without a cast. Through bptr, only the members declared in Base can be accessed.

The problem: static binding

Without virtual, the compiler picks the function from the type of the pointer, not the type of the object, because that is all it knows at compile time.

C++
#include <iostream>
using namespace std;

class Base {
public:
    void display() {
        cout << "Display base" << endl;
    }
    virtual void show() {
        cout << "Show base" << endl;
    }
    virtual ~Base() {}
};

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

int main() {
    Base B;
    Derived D;
    Base* bptr;

    cout << "bptr points to Base" << endl;
    bptr = &B;
    bptr->display(); // Base::display
    bptr->show();    // Base::show

    cout << "bptr points to Derived" << endl;
    bptr = &D;
    bptr->display(); // still Base::display: non-virtual, chosen by pointer type
    bptr->show();    // Derived::show: virtual, chosen by object type
    return 0;
}

Output:

OUTPUT
bptr points to Base
Display base
Show base
bptr points to Derived
Display base
Show derived

display() is not virtual, so bptr->display() always calls Base::display. show() is virtual, so the call follows the object.

3. Virtual Functions

A virtual function is a member function declared with the keyword virtual in the base class and redefined (overridden) in derived classes. When it is called through a base-class pointer or reference, C++ decides at run time which version to execute, based on the type of the object pointed to. This is dynamic (late) binding.

texttt{virtual} return-type function-name(arguments);

Run-time polymorphism therefore needs three things:

  1. inheritance (a base class and derived classes);
  2. a virtual function in the base class, overridden in the derived classes;
  3. a call through a base-class pointer or reference.

Calling a virtual function on an object directly (d.show()) uses static binding, since the type is already known.

A classic example: shapes

C++
#include <iostream>
using namespace std;

class Shape {
protected:
    double a, b;

public:
    Shape(double x = 0, double y = 0) : a(x), b(y) {}
    virtual double area() {
        return 0;
    }
    virtual const char* name() {
        return "Shape";
    }
    virtual ~Shape() {}
};

class Rectangle : public Shape {
public:
    Rectangle(double l, double w) : Shape(l, w) {}
    double area() {
        return a * b;
    }
    const char* name() {
        return "Rectangle";
    }
};

class Triangle : public Shape {
public:
    Triangle(double base, double h) : Shape(base, h) {}
    double area() {
        return 0.5 * a * b;
    }
    const char* name() {
        return "Triangle";
    }
};

class Circle : public Shape {
public:
    Circle(double r) : Shape(r) {}
    double area() {
        return 3.14159 * a * a;
    }
    const char* name() {
        return "Circle";
    }
};

void report(Shape& s) { // works through a reference too
    cout << s.name() << " area = " << s.area() << endl;
}

int main() {
    Shape* shapes[3];
    shapes[0] = new Rectangle(4, 5);
    shapes[1] = new Triangle(6, 3);
    shapes[2] = new Circle(1);

    double total = 0;
    for (int i = 0; i < 3; i++) {
        report(*shapes[i]); // one loop handles every kind of shape
        total = total + shapes[i]->area();
    }
    cout << "Total area = " << total << endl;

    for (int i = 0; i < 3; i++) {
        delete shapes[i];
    }
    return 0;
}

Output:

OUTPUT
Rectangle area = 20
Triangle area = 9
Circle area = 3.14159
Total area = 32.1416

The loop never mentions Rectangle, Triangle or Circle. A new shape, say Hexagon, can be added later and the loop works with it without being changed or recompiled. This is the real power of run-time polymorphism.

4. Rules for Virtual Functions

  1. Virtual functions must be members of a class.
  2. They cannot be static members.
  3. They are accessed through object pointers or references to get run-time binding.
  4. A virtual function can be a friend of another class.
  5. A virtual function in the base class must be defined (unless it is declared pure; Lesson 29).
  6. The prototypes of the base and derived versions must be identical. If they differ, C++ treats them as overloaded functions and the virtual mechanism is ignored.
  7. Constructors cannot be virtual, but destructors can (and often should be).
  8. A base pointer can point to a derived object, but not the reverse.
  9. Incrementing a base pointer does not move to the next derived object in an array of derived objects (the sizes differ).
  10. If a derived class does not redefine the virtual function, the base version is used.
  11. Once declared virtual, a function stays virtual in all further derived classes, with or without the keyword.

5. How Virtual Functions Work: vtable and vptr

Compilers implement virtual functions with two hidden structures.

StructureOne perContents
vtable (virtual table)class that has virtual functionsan array of addresses of that class's versions of each virtual function
vptr (virtual pointer)object of such a classa hidden pointer, set by the constructor, to its class's vtable

Each object's vptr points to its class's vtableEach object's vptr points to its class's vtable

A call bptr->show() becomes: follow bptr to the object, read its vptr, look up the show entry in that vtable, and call the address found there. Because the vptr belongs to the actual object, the derived version is found even through a base pointer.

The cost: each object grows by one pointer, and each virtual call has one extra indirection.

C++
#include <iostream>
using namespace std;

class Plain {
    int x;

public:
    void f() {}
};

class WithVirtual {
    int x;

public:
    virtual void f() {}
    virtual ~WithVirtual() {}
};

int main() {
    cout << "sizeof(Plain)       = " << sizeof(Plain) << endl;
    cout << "sizeof(WithVirtual) = " << sizeof(WithVirtual) << " (the int plus a hidden vptr)"
         << endl;
    return 0;
}

Output:

OUTPUT
sizeof(Plain)       = 4
sizeof(WithVirtual) = 8 (the int plus a hidden vptr)

(The second size is 16 on a 64-bit compiler, where a pointer is 8 bytes and padding is added.)

6. Static vs Dynamic Binding

Static (early) bindingDynamic (late) binding
the call is linked to a function at compile timethe call is linked at run time
used for ordinary functions, overloaded functions, and calls on objectsused for virtual functions called through pointers or references
based on the type of the pointer/referencebased on the type of the object
faster: a direct callslightly slower: a lookup through the vtable
less flexiblemore flexible: new derived classes work with old code
💡 Tip

Key points to remember

  • Overriding = same signature redefined in a derived class; overloading = same name, different parameters, same scope.
  • Without virtual, a base pointer calls the base version (static binding by pointer type).
  • With virtual, a call through a base pointer or reference runs the object's version (dynamic binding).
  • Needed: inheritance + virtual function overridden + call through base pointer/reference.
  • Implemented with a vtable per class and a vptr per object. Constructors cannot be virtual; destructors can.
🎯 END-TERM EXAM PREP

📝 IPU End-Term Exam Corner (5-10 Marks)

  • Q1. What is a virtual function? How does it achieve run-time polymorphism? Explain with a program. (10 Marks)
  • Write: the definition, the three requirements, the Base/Derived program showing display (non-virtual) and show (virtual), and the Shape program.
  • Q2. State the rules for virtual functions. (5 Marks)
  • Q3. Differentiate between function overloading and function overriding. (5 Marks)
  • Q4. Explain how virtual functions are implemented using the vtable and vptr. (5 Marks)
  • Write: the table, the diagram, the call steps, and the sizeof program.
  • Q5. Differentiate between static and dynamic binding. (2.5 Marks)