



Study with the several resources on Docsity
Earn points by helping other students or get them with a premium plan
Prepare for your exams
Study with the several resources on Docsity
Earn points to download
Earn points by helping other students or get them with a premium plan
An example of c++ inheritance using the sale and discountsale classes. It explains the concept of early binding and how an object is cast back to its base class during compile time. The document also discusses the use of virtual functions for late binding and how it allows an object to use its own methods.
Typology: Study notes
1 / 5
This page cannot be seen from the preview
Don't miss anything!




class Sale { public: Sale(); Sale(double thePrice); double GetPrice() const; void SetPrice(double newPrice); double Bill () const; double Savings (const Sale & other) const; protected: double price; };
Sale::Sale() : price (0){}
Sale :: Sale(double thePrice) { price = thePrice; }
double Sale::Bill() { return price; }
double Sale::GetPrice{} const { return price; }
void Sale::SetPrice(double newPrice) { price = newPrice; }
double Sale::Savings(const Sale & other) const { return (Bill() – other.Bill()); }
DiscountSale Class
class DiscountSale : public Sale { public: DiscountSale(); DiscountSale(double thePrice, double theDiscount);
double GetDiscount() const; void GetDiscount(double newDiscount); double Bill() const; private: double discount;
DiscountSale::DiscountSale() : Sale(0), discount (0) {}
DiscountSale::DiscountSale(double thePrice, double theDiscount):Sale(thePrice), discount(theDiscount){}
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(); }
client program:
bool operator < (const Sale& first, const Sale & second);
int main() { Sale simple(10.00); DiscountSale disc(11.00, 10);
if (disc < simple) { cout << “Discounted item is cheaper”; cout << “Saving is $” << simple.saving(discount) << endl; } else cout << “Discounted item is not cheaper.” }
bool operator < (const Sale & first, const Sale & second) { return (first.bill() < second.bill()) }
class Sale { public: Sale(); Sale(double thePrice); double GetPrice() const; void SetPrice(double newPrice); virtual double Bill () const; // Í this is the only change necessary, /* (a) if a method is defined to be virtual, then all new definitions of the function in the derived class will automatically be virtual (b) virtual modifier is not necessary in the implementation file. */ double Savings (const Sale & other) const; private: double price; };
/* output: Discounted item is cheaper Savings is $0. */
Example: class mammal {public: virtual void F(); virtual void G(); }; class dog : public mammal {public: virtual void F(); virtual void G(); }; dog MyDog;