C++: Sale prices that build on the base price

A derived class can change a member function and still use the base version inside it.

What to build

An Item class and a Sale class derived from it, where the sale price is worked out from the base price.

Requirements

  • Item keeps a name and a price, with name() and price() member functions.
  • Sale derives from Item, adds a percent, and has its own price() that calls Item::price().
  • Give Sale an originalPrice() that also uses Item::price(), and print (was P) with it for items on sale. End with the total.

Input

The first line has q. Each of the next q lines is item NAME PRICE or sale NAME PRICE PERCENT.

Output

One line per item, then total T.

Constraints

1 ≤ q ≤ 100, prices are from 0 to 100000, and percents are from 0 to 100.

Example

Input:

3
item Pen 20
sale Bag 1500 10
sale Cap 99 50

Output:

Pen 20
Bag 1350 (was 1500)
Cap 49 (was 99)
total 1419

Why it works

Item::price() reaches the base version even though Sale has its own price(). So the rule for the original price is written once, and the sale rule is built on top of it.

Examples

Example 1 · Input
3
item Pen 20
sale Bag 1500 10
sale Cap 99 50
Expected output
Pen 20
Bag 1350 (was 1500)
Cap 49 (was 99)
total 1419
Example 2 · Input
1
item Book 300
Expected output
Book 300
total 300

Hints

Hint 1

`Sale` derives from `Item` and adds a percentage.

Hint 2

Inside `Sale::price()`, call the base version by its full name, `Item::price()`, and apply the discount to it.

Hint 3

Use whole numbers: the sale price is `price * (100 - percent) / 100`.

Solution

Show one correct solution (try it yourself first)
#include <iostream>
#include <string>
using namespace std;

class Item {
protected:
    string itemName;
    int basePrice;
public:
    Item(string n, int p) : itemName(n), basePrice(p) {}
    string name() const { return itemName; }
    int price() const { return basePrice; }
};

class Sale : public Item {
    int percent;
public:
    Sale(string n, int p, int pc) : Item(n, p), percent(pc) {}
    int price() const {
        return Item::price() * (100 - percent) / 100;
    }
    int originalPrice() const {
        return Item::price();
    }
};

int main() {
    int q;
    cin >> q;
    int total = 0;
    while (q-- > 0) {
        string kind, name;
        int p;
        cin >> kind >> name >> p;
        if (kind == "item") {
            Item it(name, p);
            cout << it.name() << " " << it.price() << endl;
            total += it.price();
        } else {
            int pc;
            cin >> pc;
            Sale s(name, p, pc);
            cout << s.name() << " " << s.price() << " (was " << s.originalPrice() << ")" << endl;
            total += s.price();
        }
    }
    cout << "total " << total << endl;
    return 0;
}

Lesson: Inheritance →