Virtual Functions

Introduction

A virtual function is a special type of function that resolves to the most-derived version of the function with the same signature. To make a function virtual, simply place the “virtual” keyword before the function declaration.

Return types of virtual functions

The return type of a virtual function and it’s override must match.
However if the return type of a virtual function is a pointer or a reference to a class, override functions can return a pointer or a reference to a derived class. These are called covariant return types.

Example

class Base
{
public:
    // This version of GetThis() returns a pointer to a Base class
    virtual Base* GetThis() { return this; }
};
 
class Derived: public Base
{
    // Normally override functions have to return objects of the same type as the base function
    // However, because Derived is derived from Base, it's okay to return Derived* instead of Base*
    virtual Derived* GetThis() { return this; }
};

Examples

#include <iostream>
 
using namespace std;
 
class Base
{
        protected:
                int m_nValue;
        public:
                Base(int nValue) : m_nValue(nValue)
                {}
                virtual const char* GetName() { return "Base";}
                int GetValue() { return m_nValue; }
};
 
class Derived: public Base
{
        public:
                Derived(int nValue) : Base(nValue) {}
                virtual const char* GetName() { return "Derived"; }
                int GetValueDoubled() { return m_nValue*2; }
};
 
int main()
 
{
 
    Derived cDerived;
 
    Base &rBase = &cDerived;
 
    cout << "rBase is a " << rBase.GetName() << endl;
 
    return 0;
}

This example prints the result:

rBase is a Derived

Base::GetName() is virtual, which tells the program to go look and see if there are any more-derived versions of the function available. Because the Base object that rBase is pointing to is actually part of a Derived object, the program will check every inherited class between Base and Derived and use the most-derived version of the function that it finds.

Unless otherwise stated, the content of this page is licensed under Creative Commons Attribution-Share Alike 2.5 License.