Virtual Functions Intro
Given a classBaseClass, if one of its
member functions is declared as virtual, such a function can be
redefined in any derived class.
Consider the following function definition:
class BaseClass
{
public:
virtual void virtualFunction()
{
cout << "BaseClass virtualFunction()\n";
}
};
If a class is derived from BaseClass, it will
inherit virtualFunction() as it is. But
virtualFunction() can also be redefined
(overridden), within a derived class:
class DerivedClass: public BaseClass
{
public:
void virtualFunction()
{
cout << "DerivedClass1 virtualFunction()\n";
}
};
In this case, when an object of class DerivedClass
calls virtualFunction() the message printed
on screen will be:
DerivedClass1 virtualFunction()
Further, in case a pointer to a base class containing a virtual function is assigned an object of a derived class, if the virtual function is invoked, the version of the function being called is the derived class’ one. In the program below, for example, both
DerivedClass1
and DerivedClass2 derive from BaseClass:
class DerivedClass1: public BaseClass...
class DerivedClass2: public BaseClass...
BaseClass contains a virtual function.
DerivedClass1 and DerivedClass2
both redefine virtualFunction().
In C++ a pointer to a base class can also point to any derived class. Hence,
BaseClass *basePointer;
can point to a DerivedClass1 object, for example:
DerivedClass1 object1;
basePointer = &object1;
At this point, if the virtual function is invoked:
basePointer->virtualFunction();
the version of it overridden in DerivedClass1
will be executed, i.e. the following will be printed on screen:
DerivedClass1 virtualFunction()
When the pointer points to a
DerivedClass2
object and the virtual function is called:
DerivedClass2 object2;
basePointer = &object2;
basePointer->virtualFunction();
the code executed will be the one associated with the version of
virtualFunction() in
DerivedClass2. The following will appear on screen:
DerivedClass2 virtualFunction()
Example
#include <iostream>
#include <string>
using namespace std;
class BaseClass
{
public:
virtual void virtualFunction()
{
cout << "BaseClass virtualFunction()\n";
}
};
class DerivedClass1: public BaseClass
{
public:
void virtualFunction()
{
cout << "DerivedClass1 virtualFunction()\n";
}
};
class DerivedClass2: public BaseClass
{
public:
void virtualFunction()
{
cout << "DerivedClass2 virtualFunction()\n";
}
};
int main()
{
DerivedClass1 object1;
DerivedClass2 object2;
BaseClass *basePointer;
basePointer = &object1;
basePointer->virtualFunction();
basePointer = &object2;
basePointer->virtualFunction();
}
Output
DerivedClass1 virtualFunction() DerivedClass2 virtualFunction()