Start the library design: one abstract idea, three concrete kinds.
What to build
An abstract Item class with three kinds of item, each with its own loan period.
Requirements
- Keep the title in
Item, with a getter. - Make
loanDays()pure virtual, and override it inBook,DVDandMagazine. - Create each item with
newas anItem*, print its loan period, and delete it.
Input
The first line has q. Each of the next q lines has a kind (book, dvd or magazine) and a title of one word.
Output
One line per item: TITLE: N days.
Constraints
1 ≤ q ≤ 100.
Example
Input:
3
book Dune
dvd Cosmos
magazine Time
Output:
Dune: 14 days
Cosmos: 7 days
Time: 3 days
Why it works
Every item has a title and a loan period, but only the kind of item knows how long the period is. The abstract class captures what all items share, and each subclass supplies its own rule.
Examples
Example 1 · Input
3 book Dune dvd Cosmos magazine Time
Expected output
Dune: 14 days Cosmos: 7 days Time: 3 days
Example 2 · Input
1 magazine Weekly
Expected output
Weekly: 3 days
Hints
Hint 1
`Item` is abstract, with a pure virtual `int loanDays() const`.
Hint 2
`Book` returns 14, `DVD` returns 7 and `Magazine` returns 3.
Solution
Show one correct solution (try it yourself first)
#include <iostream>
#include <string>
using namespace std;
class Item {
string title;
public:
Item(string t) : title(t) {}
virtual ~Item() {}
string getTitle() const { return title; }
virtual int loanDays() const = 0;
};
class Book : public Item {
public:
Book(string t) : Item(t) {}
int loanDays() const override { return 14; }
};
class DVD : public Item {
public:
DVD(string t) : Item(t) {}
int loanDays() const override { return 7; }
};
class Magazine : public Item {
public:
Magazine(string t) : Item(t) {}
int loanDays() const override { return 3; }
};
int main() {
int q;
cin >> q;
while (q-- > 0) {
string kind, title;
cin >> kind >> title;
Item* it;
if (kind == "book") it = new Book(title);
else if (kind == "dvd") it = new DVD(title);
else it = new Magazine(title);
cout << it->getTitle() << ": " << it->loanDays() << " days" << endl;
delete it;
}
return 0;
}