PadhaikoAll subjects

Virtual Functions

Object Oriented Programming (ENCT 151)

Open in the Padhaiko app

6.1 What is virtual function

A virtual function is a member function declared with the keyword virtual in a base class and redefined (overridden) in a derived class. When it is called through a base class pointer or reference, C++ chooses the version to run from the type of the object pointed to, not from the type of the pointer. This is run-time polymorphism, implemented by late (dynamic) binding.

Definition

Virtual Function and Binding

Rules for virtual functions

  1. They must be members of a class (not static, not friend functions).
  2. They are accessed through a base pointer or reference to get polymorphic behaviour.
  3. The overriding function must have the same name, parameter list and return type (a covariant return is allowed). Writing override after it makes the compiler check this.
  4. The virtual keyword is needed only in the base class; the function stays virtual in all derived classes.
  5. A base class normally has a virtual destructor if it has virtual functions.
  6. If a derived class does not override the function, the base version is used.

6.2 Need of virtual function

Without virtual, a base pointer that holds the address of a derived object calls the base version, even though the object is derived. That makes it impossible to treat different objects through one common pointer type. With virtual, one loop over a list of base pointers calls the right function for every object.

Early binding versus late bindingC++
#include <iostream>
using namespace std;

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

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

int main() {
    Derived d;
    Base *p = &d;      // base pointer holding the address of a derived object
    p->show();         // early binding: decided by the pointer type
    p->display();      // late binding: decided by the object type
    Base &r = d;
    r.display();       // works with references too
    return 0;
}
OutputText
Base::show()
Derived::display()
Derived::display()

The non-virtual show() is bound by the pointer type Base *, so Base::show() runs. The virtual display() is bound by the object type, so Derived::display() runs, both through the pointer and through a reference.

Overloading, Overriding and Hiding
FeatureFunction overloadingVirtual function overriding
BindingCompile timeRun time (through base pointer or reference)
SignatureDifferent parameter listsSame name, same parameters and return type
ScopeSame classBase class and derived class
KeywordNonevirtual (and override)

6.3 Pointer to derived class

A pointer to a base class can hold the address of any object of a derived class (upcasting, an implicit conversion), but not the other way round. Through the base pointer only the members declared in the base class can be reached. To call a member that exists only in the derived class, a downcast is needed (static_cast if the type is known for certain, or dynamic_cast for a checked conversion, section 6.8).

Rules for pointers in an inheritance hierarchyC++
Base    *bp;   Derived  d;   Derived *dp;

bp = &d;      // allowed: base pointer to derived object
bp->f();      // virtual f: Derived::f; non-virtual f: Base::f
// bp->onlyInDerived();      // error: not a member of Base
dp = static_cast<Derived *>(bp);   // downcast, programmer is responsible
dp->onlyInDerived();               // now allowed

6.4 Array of pointers to base class

An array of base class pointers lets one container hold objects of different derived types and treat them in a uniform way, which is the main use of polymorphism: the loop does not need to know the exact types.

Array of pointers to a base classC++
#include <iostream>
#include <iomanip>
using namespace std;

class Shape {
public:
    virtual double area() const = 0;            // pure virtual function
    virtual const char *name() const = 0;
    virtual ~Shape() {}                          // virtual destructor
};

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

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

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

int main() {
    Shape *arr[3];                    // array of pointers to the base class
    arr[0] = new Circle(2);
    arr[1] = new Rectangle(3, 4);
    arr[2] = new Triangle(6, 5);

    double total = 0;
    cout << fixed << setprecision(2);
    for (int i = 0; i < 3; i++) {
        cout << arr[i]->name() << " area = " << arr[i]->area() << endl;
        total += arr[i]->area();
    }
    cout << "Total area = " << total << endl;
    for (int i = 0; i < 3; i++) delete arr[i];
    return 0;
}
OutputText
Circle area = 12.57
Rectangle area = 12.00
Triangle area = 15.00
Total area = 39.57

6.5 Pure virtual functions and abstract class

A pure virtual function has no body in the base class and is declared with = 0:

Syntax of a pure virtual functionC++
virtual double area() const = 0;

A class with at least one pure virtual function is an abstract class. Its objects cannot be created; it is used only as a base class and as an interface. A derived class that does not override all pure virtual functions is also abstract. A pointer or reference to an abstract class is allowed, which is what makes the array of base pointers above possible.

AspectNormal base classAbstract base class
Objects can be createdYesNo (compiler error)
Pure virtual functionNoneAt least one (= 0)
Derived class dutyOptional overridingMust override all pure virtual functions to become concrete
Typical useReuse of codeCommon interface for derived classes

6.6 Virtual destructors

If an object of a derived class is deleted through a base class pointer and the base destructor is not virtual, only the base destructor runs. The derived destructor is skipped, so derived resources leak (strictly the behaviour is undefined). Declaring the base destructor virtual makes delete call the derived destructor first and then the base destructor.

Virtual and non-virtual destructorsC++
#include <iostream>
using namespace std;

class Base {
public:
    Base()  { cout << "Base constructor" << endl; }
    ~Base() { cout << "Base destructor (non-virtual)" << endl; }
};
class Derived : public Base {
public:
    Derived()  { cout << "Derived constructor" << endl; }
    ~Derived() { cout << "Derived destructor" << endl; }
};

class VBase {
public:
    VBase()          { cout << "VBase constructor" << endl; }
    virtual ~VBase() { cout << "VBase destructor (virtual)" << endl; }
};
class VDerived : public VBase {
public:
    VDerived()  { cout << "VDerived constructor" << endl; }
    ~VDerived() { cout << "VDerived destructor" << endl; }
};

int main() {
    cout << "--- without virtual destructor ---" << endl;
    Base *p = new Derived;
    delete p;                  // undefined behaviour in standard C++, shown for illustration
    cout << "--- with virtual destructor ---" << endl;
    VBase *q = new VDerived;
    delete q;
    return 0;
}
OutputText
--- without virtual destructor ---
Base constructor
Derived constructor
Base destructor (non-virtual)
--- with virtual destructor ---
VBase constructor
VDerived constructor
VDerived destructor
VBase destructor (virtual)

Rule: if a class has any virtual function, give it a virtual destructor. Constructors cannot be virtual.

6.7 Reinterpret cast operator

reinterpret_cast<T>(expr) converts between unrelated pointer types, or between a pointer and an integer, simply by reinterpreting the bit pattern. It does no check and no adjustment, so it is the most dangerous cast and must be used only for low-level work (hardware addresses, viewing raw bytes).

C++ Cast Operators
OperatorPurposeChecked?
static_castOrdinary conversions, upcast and known downcastAt compile time
dynamic_castSafe downcast in a polymorphic hierarchyAt run time (nullptr or exception on failure)
const_castAdd or remove const or volatileAt compile time
reinterpret_castReinterpret bits of a pointer or integerNot checked

6.8 Run-time type information

Run-time type information (RTTI) lets a program find the real type of an object at run time. It works only for polymorphic classes (classes with at least one virtual function). The two tools are the typeid operator (header <typeinfo>) and dynamic_cast.

typeid, dynamic_cast and reinterpret_castC++
#include <iostream>
#include <typeinfo>
#include <cstdint>
using namespace std;

class Animal {
public:
    virtual ~Animal() {}
};
class Dog : public Animal {
public:
    void bark() { cout << "Woof!" << endl; }
};
class Cat : public Animal {};

int main() {
    Animal *a1 = new Dog;
    Animal *a2 = new Cat;

    cout << boolalpha;
    cout << "typeid(*a1) == typeid(Dog): " << (typeid(*a1) == typeid(Dog)) << endl;
    cout << "typeid(*a2) == typeid(Dog): " << (typeid(*a2) == typeid(Dog)) << endl;

    Dog *d1 = dynamic_cast<Dog *>(a1);     // succeeds
    Dog *d2 = dynamic_cast<Dog *>(a2);     // fails and returns nullptr
    cout << "dynamic_cast of a1: " << (d1 != nullptr) << endl;
    cout << "dynamic_cast of a2: " << (d2 != nullptr) << endl;
    if (d1) d1->bark();

    // reinterpret_cast: pointer -> integer -> pointer
    int x = 42;
    uintptr_t address = reinterpret_cast<uintptr_t>(&x);
    int *back = reinterpret_cast<int *>(address);
    cout << "value through the converted pointer: " << *back << endl;

    // viewing the bytes of an int through an unsigned char pointer
    unsigned int n = 0x01020304;
    unsigned char *bytes = reinterpret_cast<unsigned char *>(&n);
    cout << "first byte of 0x01020304 in memory: " << static_cast<int>(bytes[0]) << endl;

    delete a1;
    delete a2;
    return 0;
}
OutputText
typeid(*a1) == typeid(Dog): true
typeid(*a2) == typeid(Dog): false
dynamic_cast of a1: true
dynamic_cast of a2: false
Woof!
value through the converted pointer: 42
first byte of 0x01020304 in memory: 4

The last line shows 4 on a little-endian machine such as an x86 PC (the least significant byte is stored first); on a big-endian machine it would be 1.


Worked Examples

Example 1

1 (8 marks)

In the program of section 6.2 explain why p->show() prints Base::show() while p->display() prints Derived::display(), and state what changes if show() is also made virtual.

Static type and dynamic type. The pointer p has the static type Base * but points to an object whose dynamic type is Derived.

Non-virtual show(). The compiler binds the call at compile time using the static type Base *, so Base::show() is called (early binding), although the object is a Derived.

Virtual display(). The call is bound at run time. The object carries a hidden pointer to its class's virtual table (vtable), a table of the addresses of the virtual functions. The call looks up display in the vtable of the actual object, which holds Derived::display, so that version runs.

If show() is made virtual in Base, it becomes late-bound and the first line of the output would be Derived::show().

Answer:

show() is bound at compile time from the pointer type; display() is bound at run time from the object type. Making show() virtual would print Derived::show().

Example 2

2 (10 marks)

Write a program with an abstract class Shape and derived classes Circle (r = 2), Rectangle (3x4) and Triangle (base 6, height 5). Store them in an array of base pointers and print each area and the total.

Design. Shape declares the pure virtual functions area() and name() and a virtual destructor, so it cannot be instantiated. Each derived class overrides both.

Program. The complete program is the one in section 6.4. The array Shape *arr[3] holds new Circle(2), new Rectangle(3, 4) and new Triangle(6, 5); the loop calls arr[i]->area() and the right version runs each time.

Output and total. The areas are 3.14159x 2x 2 = 12.57, 3x 4 = 12.00 and 1/2x6x5 = 15.00, giving a total of 39.57, as the output shows.

Clean-up. Each object is removed with delete arr[i]. This is correct for all three types only because Shape has a virtual destructor.

Answer:

Circle 12.57, Rectangle 12.00, Triangle 15.00, total 39.57.

Example 3

3 (6 marks)

Predict the output of the program in section 6.6 and explain the difference between the two halves.

First half (non-virtual destructor). new Derived runs Base() then Derived(). The delete p through a Base * calls only ~Base() because the destructor is not virtual, so Derived destructor is never printed and the derived part of the object is not cleaned up.

Second half (virtual destructor). new VDerived runs VBase() then VDerived(). delete q finds the real type through the vtable and calls ~VDerived() first and then ~VBase(), the reverse order of construction.

Answer:

The output is as shown in section 6.6: the first half prints no derived destructor line, the second half prints both destructors, derived first.


Exercises

Exercises: Virtual Functions

Question 1

A company pays a manager basic plus allowance and a clerk by the hour. Write a program using an abstract class Employee with a pure virtual function salary(). For Manager("Sita", 50000, 12000) and Clerk("Ram", 250, 160) print each salary and the total payroll.

Program.

Abstract Employee classC++
#include <iostream>
#include <string>
using namespace std;

class Employee {
protected:
    string name;
public:
    Employee(const string &n) : name(n) {}
    virtual double salary() const = 0;        // pure virtual
    void print() const { cout << name << ": " << salary() << endl; }
    virtual ~Employee() {}
};

class Manager : public Employee {
    double basic, allowance;
public:
    Manager(const string &n, double b, double a) : Employee(n), basic(b), allowance(a) {}
    double salary() const override { return basic + allowance; }
};

class Clerk : public Employee {
    double perHour; int hours;
public:
    Clerk(const string &n, double p, int h) : Employee(n), perHour(p), hours(h) {}
    double salary() const override { return perHour * hours; }
};

int main() {
    Employee *staff[2] = { new Manager("Sita", 50000, 12000), new Clerk("Ram", 250, 160) };
    double total = 0;
    for (int i = 0; i < 2; i++) {
        staff[i]->print();
        total += staff[i]->salary();
    }
    cout << "Total payroll: " << total << endl;
    for (int i = 0; i < 2; i++) delete staff[i];
    return 0;
}

Output. The manager earns 50000 + 12000 = 62000 and the clerk 250x160 = 40000, so the payroll is 102000.

OutputText
Sita: 62000
Ram: 40000
Total payroll: 102000
Answer:

Sita 62000, Ram 40000, total payroll 102000.

Question 2

Find the output of the following program and explain every line.

Program.

Virtual and non-virtual calls in a hierarchyC++
#include <iostream>
using namespace std;

class A {
public:
    virtual void f() { cout << "A::f" << endl; }
    virtual void g() { cout << "A::g" << endl; }
    void h()         { cout << "A::h" << endl; }
};
class B : public A {
public:
    void f() override { cout << "B::f" << endl; }   // g is not overridden
    void h()          { cout << "B::h" << endl; }
};
class C : public B {
public:
    void g() override { cout << "C::g" << endl; }
};

int main() {
    C obj;
    A *p = &obj;
    p->f();
    p->g();
    p->h();
    B *q = &obj;
    q->f();
    q->h();
    return 0;
}

Output.

OutputText
B::f
C::g
A::h
B::f
B::h

p->f(): f is virtual and overridden in B; the object is a C, which inherits B::f, so B::f runs. p->g(): g is virtual and overridden in C, so C::g runs. p->h(): h is not virtual, so the pointer type A * decides and A::h runs. q->f() again gives B::f, and q->h() gives B::h because the pointer type is B *.

Answer:

B::f, C::g, A::h, B::f, B::h

Question 3

What is an abstract class? Why does the statement Shape s; fail when Shape has a pure virtual function, and how do you make a derived class concrete?

An abstract class has at least one pure virtual function (= 0). It represents an incomplete concept and is meant only as a base class.

Shape s; would create an object that has a function with no body, so the compiler refuses it with an error such as "cannot declare variable 's' to be of abstract type 'Shape'". Pointers and references to Shape are still allowed.

A derived class becomes concrete (its objects can be created) when it overrides every pure virtual function inherited from the abstract class and supplies a body for each.

Answer:

An abstract class has a pure virtual function; its objects cannot be created. A derived class must override all pure virtual functions to become concrete.

Question 4

An array of five Animal pointers holds Dog, Cat, Dog, Dog, Cat. Write a program that counts the dogs and cats using RTTI.

Program. dynamic_cast<Dog *> returns a non-null pointer only for real Dog objects, so the test counts them. Animal has a virtual destructor, which makes it polymorphic as RTTI requires.

Counting types with dynamic_castC++
#include <iostream>
using namespace std;

class Animal { public: virtual ~Animal() {} };
class Dog : public Animal {};
class Cat : public Animal {};

int main() {
    Animal *zoo[5] = { new Dog, new Cat, new Dog, new Dog, new Cat };
    int dogs = 0, cats = 0;
    for (int i = 0; i < 5; i++) {
        if (dynamic_cast<Dog *>(zoo[i])) dogs++;
        else if (dynamic_cast<Cat *>(zoo[i])) cats++;
    }
    cout << "Dogs = " << dogs << ", Cats = " << cats << endl;
    for (int i = 0; i < 5; i++) delete zoo[i];
    return 0;
}

Output.

OutputText
Dogs = 3, Cats = 2
Answer:

Dogs = 3, Cats = 2

Question 5

What problem arises if a class with virtual functions has a non-virtual destructor and an object is deleted through a base pointer? How is it solved? Can a constructor be virtual?

Only the base destructor runs. Members that are owned by the derived part (dynamic memory, open files) are never released, which causes leaks, and the standard calls the behaviour undefined.

The solution is to declare the base destructor virtual, so that delete basePtr calls the destructor of the actual derived type first and then the base destructor.

A constructor cannot be virtual: virtual dispatch needs the vptr, and the vptr is set up by the constructor itself, so the object's type must already be known when it is constructed.

Answer:

Without a virtual destructor the derived destructor is skipped and resources leak; use virtual ~Base(). Constructors cannot be virtual.

← InheritanceStream Computation →