Home > Articles > Programming > C/C++

Polymorphic and Virtual Functions in C++

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
    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.
    double price;

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


#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;
      cout << "Error: Cannot have a negative price!\n";

  double Sale::bill( ) const
    return price;

  double Sale::getPrice( ) const
    return price;

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


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

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


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.

#include "sale.h"

namespace SavitchSale

  class DiscountSale : public Sale

    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;
    double discount;




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( );


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.


  if (discount < simple)
    cout << "Discounted item is cheaper.\n";
    cout << "Savings is $" << simple.savings(discount) << endl;
    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

    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;
    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( )

#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.

InformIT Promotional Mailings & Special Offers

I would like to receive exclusive offers and hear about products from InformIT and its family of brands. I can unsubscribe at any time.


Pearson Education, Inc., 221 River Street, Hoboken, New Jersey 07030, (Pearson) presents this site to provide information about products and services that can be purchased through this site.

This privacy notice provides an overview of our commitment to privacy and describes how we collect, protect, use and share personal information collected through this site. Please note that other Pearson websites and online products and services have their own separate privacy policies.

Collection and Use of Information

To conduct business and deliver products and services, Pearson collects and uses personal information in several ways in connection with this site, including:

Questions and Inquiries

For inquiries and questions, we collect the inquiry or question, together with name, contact details (email address, phone number and mailing address) and any other additional information voluntarily submitted to us through a Contact Us form or an email. We use this information to address the inquiry and respond to the question.

Online Store

For orders and purchases placed through our online store on this site, we collect order details, name, institution name and address (if applicable), email address, phone number, shipping and billing addresses, credit/debit card information, shipping options and any instructions. We use this information to complete transactions, fulfill orders, communicate with individuals placing orders or visiting the online store, and for related purposes.


Pearson may offer opportunities to provide feedback or participate in surveys, including surveys evaluating Pearson products, services or sites. Participation is voluntary. Pearson collects information requested in the survey questions and uses the information to evaluate, support, maintain and improve products, services or sites, develop new products and services, conduct educational research and for other purposes specified in the survey.

Contests and Drawings

Occasionally, we may sponsor a contest or drawing. Participation is optional. Pearson collects name, contact information and other information specified on the entry form for the contest or drawing to conduct the contest or drawing. Pearson may collect additional personal information from the winners of a contest or drawing in order to award the prize and for tax reporting purposes, as required by law.


If you have elected to receive email newsletters or promotional mailings and special offers but want to unsubscribe, simply email information@informit.com.

Service Announcements

On rare occasions it is necessary to send out a strictly service related announcement. For instance, if our service is temporarily suspended for maintenance we might send users an email. Generally, users may not opt-out of these communications, though they can deactivate their account information. However, these communications are not promotional in nature.

Customer Service

We communicate with users on a regular basis to provide requested services and in regard to issues relating to their account we reply via email or phone in accordance with the users' wishes when a user submits their information through our Contact Us form.

Other Collection and Use of Information

Application and System Logs

Pearson automatically collects log data to help ensure the delivery, availability and security of this site. Log data may include technical information about how a user or visitor connected to this site, such as browser type, type of computer/device, operating system, internet service provider and IP address. We use this information for support purposes and to monitor the health of the site, identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents and appropriately scale computing resources.

Web Analytics

Pearson may use third party web trend analytical services, including Google Analytics, to collect visitor information, such as IP addresses, browser types, referring pages, pages visited and time spent on a particular site. While these analytical services collect and report information on an anonymous basis, they may use cookies to gather web trend information. The information gathered may enable Pearson (but not the third party web trend services) to link information with application and system log data. Pearson uses this information for system administration and to identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents, appropriately scale computing resources and otherwise support and deliver this site and its services.

Cookies and Related Technologies

This site uses cookies and similar technologies to personalize content, measure traffic patterns, control security, track use and access of information on this site, and provide interest-based messages and advertising. Users can manage and block the use of cookies through their browser. Disabling or blocking certain cookies may limit the functionality of this site.

Do Not Track

This site currently does not respond to Do Not Track signals.


Pearson uses appropriate physical, administrative and technical security measures to protect personal information from unauthorized access, use and disclosure.


This site is not directed to children under the age of 13.


Pearson may send or direct marketing communications to users, provided that

  • Pearson will not use personal information collected or processed as a K-12 school service provider for the purpose of directed or targeted advertising.
  • Such marketing is consistent with applicable law and Pearson's legal obligations.
  • Pearson will not knowingly direct or send marketing communications to an individual who has expressed a preference not to receive marketing.
  • Where required by applicable law, express or implied consent to marketing exists and has not been withdrawn.

Pearson may provide personal information to a third party service provider on a restricted basis to provide marketing solely on behalf of Pearson or an affiliate or customer for whom Pearson is a service provider. Marketing preferences may be changed at any time.

Correcting/Updating Personal Information

If a user's personally identifiable information changes (such as your postal address or email address), we provide a way to correct or update that user's personal data provided to us. This can be done on the Account page. If a user no longer desires our service and desires to delete his or her account, please contact us at customer-service@informit.com and we will process the deletion of a user's account.


Users can always make an informed choice as to whether they should proceed with certain services offered by InformIT. If you choose to remove yourself from our mailing list(s) simply visit the following page and uncheck any communication you no longer want to receive: www.informit.com/u.aspx.

Sale of Personal Information

Pearson does not rent or sell personal information in exchange for any payment of money.

While Pearson does not sell personal information, as defined in Nevada law, Nevada residents may email a request for no sale of their personal information to NevadaDesignatedRequest@pearson.com.

Supplemental Privacy Statement for California Residents

California residents should read our Supplemental privacy statement for California residents in conjunction with this Privacy Notice. The Supplemental privacy statement for California residents explains Pearson's commitment to comply with California law and applies to personal information of California residents collected in connection with this site and the Services.

Sharing and Disclosure

Pearson may disclose personal information, as follows:

  • As required by law.
  • With the consent of the individual (or their parent, if the individual is a minor)
  • In response to a subpoena, court order or legal process, to the extent permitted or required by law
  • To protect the security and safety of individuals, data, assets and systems, consistent with applicable law
  • In connection the sale, joint venture or other transfer of some or all of its company or assets, subject to the provisions of this Privacy Notice
  • To investigate or address actual or suspected fraud or other illegal activities
  • To exercise its legal rights, including enforcement of the Terms of Use for this site or another contract
  • To affiliated Pearson companies and other companies and organizations who perform work for Pearson and are obligated to protect the privacy of personal information consistent with this Privacy Notice
  • To a school, organization, company or government agency, where Pearson collects or processes the personal information in a school setting or on behalf of such organization, company or government agency.


This web site contains links to other sites. Please be aware that we are not responsible for the privacy practices of such other sites. We encourage our users to be aware when they leave our site and to read the privacy statements of each and every web site that collects Personal Information. This privacy statement applies solely to information collected by this web site.

Requests and Contact

Please contact us about this Privacy Notice or if you have any requests or questions relating to the privacy of your personal information.

Changes to this Privacy Notice

We may revise this Privacy Notice through an updated posting. We will identify the effective date of the revision in the posting. Often, updates are made to provide greater clarity or to comply with changes in regulatory requirements. If the updates involve material changes to the collection, protection, use or disclosure of Personal Information, Pearson will provide notice of the change through a conspicuous notice on this site or other appropriate way. Continued use of the site after the effective date of a posted revision evidences acceptance. Please contact us if you have questions or concerns about the Privacy Notice or any objection to any revisions.

Last Update: November 17, 2020