web analytics

Understanding Polymorphism and Virtual Functions in C++

Options

codeling 1602 - 6666
@2016-02-28 13:26:15

What is Polymorphism in C++?

Togethor with abstraction and  inheritance, polymorphism is one of the fundamental mechanisms of a popular and powerful programming philosophy known as object oriented programming. Polymorphism may be defined as the ability of related objects to respond to the same message with different, but appropriate actions. In other words, polymorphism means taking more than one form.  For example, a base class pointer can point to its child class and a base class array can store different child class objects.

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. The following sections will explain them.

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.

@2016-02-28 13:28:35

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!
";
      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!
";
      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.
";
    cout << "Savings is ___FCKpd___4quot; << simple.savings(discount) << endl;
  }
  else
    cout << "Discounted item is not cheaper.
";

  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 
@2016-03-05 13:12:28

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.

@2016-03-05 13:13:12

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.

Comments

You must Sign In to comment on this topic.


© 2024 Digcode.com