Inheritance/Polymorphism  «Prev  Next»
Lesson 9 Virtual functions
Objective Describe how virtual functions can be used to implement reusable code.

Virtual Functions in C++

The keyword virtual is a function specifier that causes function call selection at runtime, and it can only be used to modify member function declarations. The combination of virtual functions and public inheritance will be our most general and flexible way to build a piece of software. This is a form of pure polymorphism. Virtual functions allow runtime decisions. Consider a computer-aided design application in which the area of the shapes in a design has to be computed. The different shapes will be derived from the shape base class:

class shape {
   virtual double  area() const { return 0; }
   //virtual double area is default behavior
   double  x, y;

class rectangle : public shape {
   double  area() const { return (height * width); }
   double  height, width;

class circle : public shape {
   double  area() const
     { return (PI * radius * radius);}
   double   radius;

In such a class hierarchy, the derived classes correspond to important, well understood types of shapes. The system is readily expanded by deriving further classes. The area calculation is a local responsibility of a derived class. Client code that uses the polymorphic area calculation looks like this:

shape*  p[N];

for (i = 0; i < N; ++i)
    tot_area += p[i] -> area();

A major advantage here is that the client code will not need to change if new shapes are added to the system. Change is managed locally and propagated automatically by the polymorphic character of the client code.