6.15 Pointers and virtual functions 191
If instead we include in the public section of the flower the non-virtual
functionprintrtypeimplementation:
void printrtype() const{};
then the statement
pointer2 -> printrtype();
will invoke theprintrtypefunction of the flower class, which is idle.
When a virtual function is declared, a v-table is constructed for the class
consisting of addresses to the virtual functions for classes and pointers to the
functions from each of the objects of the derived class. Whenever a function
call is made to the virtual function, the v-table is used to resolve to the function
address by way ofdynamic binding.
Virtual functions exemplify intriguing concepts underlying the notion of
object-oriented programming. A class that declares or inherits virtual functions
is called apolymorphic.
Student tuition
The following code exemplifies the use of virtual functions with a base
class of students and two derived classes of resident and non-resident students.
For convenience, the class definition and implementation are consolidated. The
base class is defined and implemented as:
#include <iostream>
using namespace std;
//--- STUDENT CLASS
class student
{
public:
virtual void payment()=0;
};
Note that the base class is endowed with only one idle virtual function, and lacks
a constructor. A class with such minimum functionality is called anabstract
base class.