Dynamic Binding

Through dynamic binding, we can use the same code to process objects of either type Quote or Bulk_quote interchangeably. For example, the following function prints the total price for purchasing the given number of copies of a given book:

// calculate and print the price for the given number of copies, applying any discounts
double print_total(ostream &os,
                   const Quote &item, size_t n)
{
    // depending on the type of the object bound to the item parameter
    // calls either Quote::net_price or Bulk_quote::net_price
    double ret = item.net_price(n);
    os << "ISBN: " << item.isbn() // calls Quote::isbn
       << " # sold: " << n << " total due: " << ret << endl;
     return ret;
}

This function is pretty simple—it prints the results of calling isbn and net_price on its parameter and returns the value calculated by the call to net_price.

Nevertheless, there are two interesting things about this function: For reasons we’ll explain in § 15.2.3 (p. 601), because the item parameter is a reference to Quote, we can call this function on either a Quote object or a Bulk_quote object. And, for reasons we’ll explain in § 15.2.1 (p. 594), because net_price is a virtual function, and because print_total calls net_price through a reference, the version of net_price that is run will depend on the type of the object that we pass to print_total:

// basic has type Quote; bulk has type Bulk_quote
print_total(cout, basic, 20); //  calls Quote version of net_price
print_total(cout, bulk, 20);  //  calls Bulk_quote version of net_price

The first call passes a Quote object to print_total. When print_total calls net_price, the Quote version will be run. In the next call, the argument is a Bulk_quote, so the Bulk_quote version of net_price (which applies a discount) will be run. Because the decision as to which version to run depends on the type of the argument, that decision can’t be made until run time. Therefore, dynamic binding is sometimes known as run-time binding.


Image Note

In C++, dynamic binding happens when a virtual function is called through a reference (or a pointer) to a base class.


..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.141.197.251