Home > Articles > Programming > C/C++

Polymorphic and Virtual Functions in C++

  • Print
  • + Share This
Polymorphism refers to the capability to associate many meanings to one function name by means of a special mechanism known as a virtual function, or late binding. Walter Savitch discusses the basics in this article.
This article is derived from Absolute C++ (Addison-Wesley, 2002), by Walter Savitch.
This chapter is from the book

This chapter is from the book

I did it my way.
—Frank Sinatra

Polymorphism refers to the ability to associate many meanings to one function name by means of a special mechanism known as virtual functions or late binding. Polymorphism is one of the fundamental mechanisms of a popular and powerful programming philosophy known as object oriented programming. Wow, lots of fancy words! This article will explain them.

Virtual Function Basics

virtual adj. 1. Existing or resulting in essence or effect though not in actual fact, form, or name...
—The American Heritage Dictionary of The English Language, Third Edition

A virtual function is so named because it may, in a sense to be made clear, be used before it is defined. Virtual functions will prove to be another tool for software reuse.

Late Binding

Virtual functions are best explained by am example. Suppose you are designing software for a graphics package that has classes for several kinds of figures, such as rectangles, circles, ovals, and so forth. Each figure might be an object of a different class. For example, the Rectangle class might have member variables for a height, width, and center point, while the Circle class might have member variables for a center point and a radius. In a well-designed programming project, all of them would probably be descendents of a single parent class called, for example, Figure. Now, suppose you want a function to draw a figure on the screen. To draw a circle, you need different instructions from those you need to draw a rectangle. So, each class needs to have a different function to draw its kind of figure. However, because the functions belong to the classes, they can all be called draw. If r is a Rectangle object and c is a Circle object, then r.draw( ) and c.draw( ) can be functions implemented with different code. All this is not news, but now we move on to something new: virtual functions defined in the parent class Figure.

Now, the parent class Figure may have functions that apply to all figures. For example, it might have a function called center that moves a figure to the center of the screen by erasing it and then redrawing it in the center of the screen. The function Figure::center might use the function draw to redraw the figure in the center of the screen. When you think of using the inherited function center with figures of the classes Rectangle and Circle, you begin to see that there are complications here.

To make the point clear and more dramatic, let's suppose the class Figure is already written and in use and at some later time you add a class for a brand new kind of figure, say the class Triangle. Now Triangle can be a derived class of the class Figure, and so the function center will be inherited from the class Figure and so the function center should apply to (and perform correctly for!) all Triangles. But there is a complication. The function center uses draw, and the function draw is different for each type of figure. The inherited function center (if nothing special is done) will use the definition of the function draw given in the class Figure, and that function draw does not work correctly for Triangles. We want the inherited member function center to use the function Triangle::draw rather than the function Figure::draw. But the class Triangle and so the function Triangle::draw was not even written when the function center (defined in the class Figure) was written and even compiled! How can the function center possibly work correctly for Triangles? The compiler did not know anything about Triangle::draw at the time that center was compiled! The answer is that it can apply provided draw is a virtual function.

When you make a function virtual, you are telling the compiler "I do not know how this function is implemented. Wait until it is used in a program, and then get the implementation from the object instance." The technique of waiting until run time to determine the implementation of a function is often called late binding or dynamic binding. Virtual functions are the way C++ provides late binding. But enough introduction. We need an example to make this come alive (and to teach you how to use virtual functions in your programs). In order to explain the details of virtual functions in C++, we will use a simplified example from an application area other than drawing figures.

Virtual Functions in C++

Suppose you are designing a record-keeping program for an automobile parts store. You want to make the program versatile, but you are not sure you can account for all possible situations. For example, you want to keep track of sales, but you cannot anticipate all types of sales. At first, there will only be regular sales to retail customers who go to the store to buy one particular part. However, later you may want to add sales with discounts or mail order sales with a shipping charge. All these sales will be for an item with a basic price and ultimately will produce some bill. For a simple sale, the bill is just the basic price, but if you later add discounts, then some kinds of bills will also depend on the size of the discount. Now your program will need to compute daily gross sales, which intuitively should just be the sum of all the individual sales bills. You may also want to calculate the largest and smallest sales of the day or the average sale for the day. All these can be calculated from the individual bills, but many of the functions for computing the bills will not be added until later, when you decide what types of sales you will be dealing with. To accommodate this, we make the function for computing the bill a virtual function. (For simplicity in this first example, we assume that each sale is for just one item, although with derived classes and virtual functions we could, but will not here, account for sales of multiple items.)

Displays 1 and 2 contain the interface and implement for the class Sale.

Display 1—Interface for the Base Class Sale

//This is the header file sale.h. 
//This is the interface for the class Sale.
//Sale is a class for simple sales.

#ifndef SALE_H
#define SALE_H

namespace SavitchSale
{

  class Sale
  {
  public:
    Sale( );
    Sale(double thePrice);
    double getPrice( ) const;
    void setPrice(double newPrice);
    virtual double bill( ) const;
    double savings(const Sale& other) const;
    //Returns the savings if you buy other instead of the calling object.
  private:
    double price;
  };

  bool operator < (const Sale& first, const Sale& second);
  //Compares two sales to see which is larger.

}//SavitchSale

#endif // SALE_H

Display 2—Implementation of the Base Class Sale

//This is the file sale.cpp.
//This is the implementation for the class Sale.
//The interface for the class Sale is in the file sale.h.

#include <iostream>
#include "sale.h"
using std::cout;

namespace SavitchSale
{

  Sale::Sale( ) : price(0)
  {
    //Intentionally empty
  } 

  Sale::Sale(double thePrice)
  {
    if (thePrice >= 0)
      price = thePrice;
    else
    {
      cout << "Error: Cannot have a negative price!\n";
      exit(1);
    }
  }

  double Sale::bill( ) const
  {
    return price;
  }

  double Sale::getPrice( ) const
  {
    return price;
  }

  void Sale::setPrice(double newPrice)
  {
    if (newPrice >= 0)
      price = newPrice;
    else
    {
      cout << "Error: Cannot have a negative price!\n";
      exit(1);

    }
  }

  double Sale::savings(const Sale& other) const
  {
    return (bill( ) - other.bill( ));
  }

  bool operator < (const Sale& first, const Sale& second)
  {
    return (first.bill( ) < second.bill( ));
  }

}//SavitchSale

For example, Displays 3 and 4 show the derived class DiscountSale.

Display 3—Interface for the Derived Class DiscountSale

//This is the file discountsale.h.
//This is the interface for the class DiscountSale.

#ifndef DISCOUNTSALE_H
#define DISCOUNTSALE_H
#include "sale.h"

namespace SavitchSale
{

  class DiscountSale : public Sale
  {

  public:
    DiscountSale( );
    DiscountSale(double thePrice, double theDiscount);
    //Discount is expressed as a percent of the price.
    //A negative discount is a price increase.
    double getDiscount( ) const;
    void setDiscount(double newDiscount);
    double bill( ) const;
  private:
    double discount;

  };

}//SavitchSale

#endif //DISCOUNTSALE_H

Display 4—Implementation for the Derived Class DiscountSale

//This is the implementation for the class DiscountSale.
//This is the file discountsale.cpp.
//The interface for the class DiscountSale is in the header file discountsale.h.
#include "discountsale.h"

namespace SavitchSale
{

  DiscountSale::DiscountSale( ) : Sale( ), discount(0)
  {
    //Intentionally empty
  } 

  DiscountSale::DiscountSale(double thePrice, double theDiscount)
       : Sale(thePrice), discount(theDiscount)
  {
    //Intentionally empty
  } 

  double DiscountSale::getDiscount( ) const
  {
    return discount;
  }

  void DiscountSale::setDiscount(double newDiscount)
  {
    discount = newDiscount;
  }

  double DiscountSale::bill( ) const
  {
    double fraction = discount/100;
    return (1 - fraction)*getPrice( );
  }

}//SavitchSale

How does this work? In order to write C++ programs, you can just assume it happens by magic, but the real explanation was given in the introduction to this section. When you label a function virtual, you are telling the C++ environment "Wait until this function is used in a program, and then get the implementation corresponding to the calling object."

Display 5 gives a sample program that illustrates the virtual function.

Display 5—Use of a Virtual Function

//Demonstrates the performance of the virtual function bill.
#include <iostream>
#include "sale.h" //Not really needed, but safe due to ifndef.
#include "discountsale.h"
using std::cout;
using std::endl;
using std::ios;
using namespace SavitchSale;

int main( )
{
  Sale simple(10.00);//One item at $10.00.
  DiscountSale discount(11.00, 10);//One item at $11.00 with a 10% discount.

  cout.setf(ios::fixed);
  cout.setf(ios::showpoint);
  cout.precision(2);

  if (discount < simple)
  {
    cout << "Discounted item is cheaper.\n";
    cout << "Savings is $" << simple.savings(discount) << endl;
  }
  else
    cout << "Discounted item is not cheaper.\n";

  return 0;
}
//The objects discount and simple use different code for the member function 
//bill when the less-than comparison is made. Similar remarks apply to savings.

Sample Dialogue

Discounted item is cheaper.
Savings is $0.10 

Programming Tip: The Virtual Property Is Inherited

The property of being a virtual function is inherited. For example, since bill was declared to be virtual in the base class Sale (Display 1), the function bill is automatically virtual in the derived class DiscountSale (refer to Display 3). So, the following two declarations of the member function bill would be equivalent in the definition of the derived class DiscountSale:

double bill( ) const;
virtual double bill( ) const;

Thus, if SuperDiscountSale is a derived class of the class DiscountSale that inherits the function savings, and if the function bill is given a new definition for the class SuperDiscountSale, then all objects of the class SuperDiscountSale will use the definition of the function bill given in the definition of the class SuperDiscountSale. Even the inherited function savings (which includes a call to the function bill) will use the definition of bill given in SuperDiscountSale whenever the calling object is in the class SuperDiscountSale.

Programming Tip: When to Use a Virtual Function

There are clear advantages to using virtual functions and no clear disadvantages that we have seen so far. So, why not make all member functions virtual? In fact, why not define the C++ compiler so that (like some other languages, such as Java) all member functions are automatically virtual? The answer is that there is a large overhead to making a function virtual. It uses more storage and makes your program run slower than if the function were not virtual. That is why the designers of C++ gave the programmer control over which member functions are virtual and which are not. If you expect to need the advantages of a virtual member function, then make that member function virtual. If you do not expect to need the advantages of a virtual function, then your program will run more efficiently if you do not make the member function virtual.

Pitfall: Omitting the Definition of a Virtual Member Function

It is wise to develop incrementally. This means code a little, test a little, then code a little more, and test a little more, and so forth. However, if you try to compile classes with virtual member functions, but do not implement each member, you may run into some very-hard-to-understand error messages, even if you do not call the undefined member functions!

If any virtual member functions are not implemented before compiling, then the compilation fails with error messages similar to this:

Undefined reference to Class_Name virtual table.

Even if there is no derived class and there is only one virtual member function, but that function does not have a definition, then this kind of message still occurs.

What makes the error messages very hard to decipher is that without definitions for the functions declared virtual, there will be further error messages complaining about an undefined reference to default constructors, even if these constructors really are already defined.

Of course, you may use some trivial definition for a virtual function until you are ready to define the "real" version of the function.

This caution does not apply to pure virtual functions, which we discuss in the next section. As you will see, pure virtual functions are not supposed to have a definition.

Abstract Classes and Pure Virtual Functions

You can encounter situations where you want to have a class to use as a base class for a number of other classes, but you do not have any meaningful definition to give to one or more of its member functions. When we introduced virtual functions we discussed one such scenario. Let's review it now.

Suppose you are designing software for a graphics package that has classes for several kinds of figures, such as rectangles, circles, ovals, and so forth. Each figure might be an object of a different class, such as the Rectangle class or the Circle class. In a well-designed programming project, all of them would probably be descendents of a single parent class called, for example, Figure. Now, suppose you want a function to draw a figure on the screen. To draw a circle, you need different instructions from those you need to draw a rectangle. So, each class needs to have a different function to draw its kind of figure. If r is a Rectangle object and c is a Circle object, then r.draw( ) and c.draw( ) can be functions implemented with different code.

Now, the parent class Figure may have a function called center that moves a figure to the center of the screen by erasing it and then redrawing it in the center of the screen. The function Figure::center might use the function draw to redraw the figure in the center of the screen. By making the member function draw a virtual function, you can write the code for the member function Figure::center in the class Figure and know that when it is used for a derived class, say Circle, the definition of draw in the class Circle will be the definition used. You never plan to create an object of type Figure. You only intend to create objects of the derived classes such as Circle and Rectangle. So, the definition that you give to Figure::draw will never be used. However, based only on what we covered so far, you would still need to give a definition for Figure::draw, even though it could be trivial.

If you make the member function Figure::draw a pure virtual function, then you do not need to give any definition to that member function. The way you make a member function into a pure virtual function is to mark it virtual and to add the annotation = 0 to the member function declaration as in the following example:

virtual void draw( ) = 0;

Any kind of member can be made a pure virtual function. It need not be a void function with no parameters as in our example.

A class with one or more pure virtual functions is called an abstract class. An abstract class can only be used as a base class to derive other classes. You cannot create objects of an abstract class, since it is not a complete class definition. An abstract class is a partial class definition because it can contain other member functions that are not pure virtual functions. An abstract class is also a type, so you can write code with parameters of the abstract class type and it will apply to all objects of classes that are descendents of the abstract class.

If you derive a class from an abstract class it will itself be an abstract class unless you provide definitions for all the inherited pure virtual functions (and also do not introduce any new pure virtual functions). If you do provide definitions for all the inherited pure virtual functions (and also do not introduce any new pure virtual functions) the resulting class is a not an abstract class, which means you can create objects of the class.

Programming Example: An Abstract Class

Display 6 shows the interface for the class Employee.

Display 6—Interface for the Abstract Class Employee

//This is the header file employee.h. 
//This is the interface for the abstract class Employee.

#ifndef EMPLOYEE_H
#define EMPLOYEE_H

#include <string>
using std::string;

namespace SavitchEmployees
{

  class Employee
  {

  public:
    Employee( );
    Employee(string theName, string theSsn);
    string getName( ) const;
    string getSsn( ) const;
    double getNetPay( ) const;
    void setName(string newName); 
    void setSsn(string newSsn);
    void setNetPay(double newNetPay);
    virtual void printCheck( ) const = 0;
  private:
    string name; 
    string ssn; 
    double netPay;

  };
//The implementation for this class is the same as in Chapter 14, 
//except that no definition is given for the member function printCheck( )
}//SavitchEmployees

#endif //EMPLOYEE_H

The word virtual and the = 0 in the member function heading tell the compiler this is a pure virtual function and so the class Employee is now an abstract class. The implementation for the class Employee includes no definition for the class Employee::printCheck (but otherwise the implementation of the class Employee is the same as before).

It makes sense that there is no definition for the member function Employee::printCheck, since you do not know what kind of check to write until know what kind of employee you are dealing with.

  • + Share This
  • 🔖 Save To Your Account