C++ · Module 19 · Lesson 31 min read

Project: Library System with Inheritance

Features checklist

  1. Item types: Book (21 days, Rs. 5/day fine), DVD (7 days, Rs. 20/day), Magazine (reference only — can't be borrowed)
  2. Members with a borrowing limit
  3. Borrow and return with due dates and late fines
  4. Search the catalogue by title keyword
  5. Reports: items on loan, overdue items, total fines collected
  6. Catalogue stored as std::vector<std::unique_ptr<Item>>

Class design

arduino
class Item (abstract)
    virtual int loan_days() const = 0;
    virtual int fine_per_day() const = 0;
    virtual bool can_borrow() const { return true; }
    virtual std::string type() const = 0;
├── Book      (author, pages)
├── DVD       (minutes)
└── Magazine  (issue)  — can_borrow() returns false
class Member { id, name, borrowed count, limit }
class Library { items, members, borrow(), give_back(), reports }

Concepts practised

Abstract base classes, pure virtual functions, override, virtual destructor, std::unique_ptr for polymorphic objects, std::map for members, dynamic_cast for type-specific details, case-insensitive search, exceptions for rule violations.

Why inheritance fits here

Every item is an Item with the same operations (borrow, return, fine), but different rules. New types (e-book, board game) can be added without changing Library code (Open/Closed principle).

Extensions

Reservations queue per item (std::queue), real dates with <chrono>, saving the catalogue to a file, renewals, member history.

Example

C++
#include <algorithm>
#include <cctype>
#include <format>
#include <iostream>
#include <map>
#include <memory>
#include <stdexcept>
#include <string>
#include <vector>

class Item {
public:
    Item(int id, std::string title) : id_(id), title_(std::move(title)) {}
    virtual ~Item() = default;
    virtual std::string type() const = 0;
    virtual int loan_days() const = 0;
    virtual int fine_per_day() const = 0;
    virtual bool can_borrow() const { return true; }
    virtual std::string details() const { return ""; }

    int id() const { return id_; }
    const std::string& title() const { return title_; }
    bool on_loan() const { return borrower_ != 0; }
    int borrower() const { return borrower_; }
    int due_day() const { return due_day_; }
    void lend(int member, int today) { borrower_ = member; due_day_ = today + loan_days(); }
    int give_back(int today) {
        int late = std::max(0, today - due_day_);
        borrower_ = 0;
        return late * fine_per_day();
    }
private:
    int id_;
    std::string title_;
    int borrower_ = 0, due_day_ = 0;
};

class Book : public Item {
public:
    Book(int id, std::string title, std::string author) : Item(id, std::move(title)), author_(std::move(author)) {}
    std::string type() const override { return "Book"; }
    int loan_days() const override { return 21; }
    int fine_per_day() const override { return 5; }
    std::string details() const override { return "by " + author_; }
private:
    std::string author_;
};

class DVD : public Item {
public:
    DVD(int id, std::string title, int minutes) : Item(id, std::move(title)), minutes_(minutes) {}
    std::string type() const override { return "DVD"; }
    int loan_days() const override { return 7; }
    int fine_per_day() const override { return 20; }
    std::string details() const override { return std::to_string(minutes_) + " min"; }
private:
    int minutes_;
};

class Magazine : public Item {
public:
    using Item::Item;
    std::string type() const override { return "Magazine"; }
    int loan_days() const override { return 0; }
    int fine_per_day() const override { return 0; }
    bool can_borrow() const override { return false; }           // reference only
};

struct Member { std::string name; int limit; int borrowed = 0; };

class Library {
public:
    template <typename T, typename... Args>
    void add(Args&&... args) { items_.push_back(std::make_unique<T>(next_id_++, std::forward<Args>(args)...)); }
    void join(int id, std::string name, int limit) { members_[id] = { std::move(name), limit }; }

    void borrow(int member_id, int item_id, int today) {
        Member& m = members_.at(member_id);
        Item& it = find(item_id);
        if (!it.can_borrow()) throw std::runtime_error(it.title() + " is reference only");
        if (it.on_loan()) throw std::runtime_error(it.title() + " is already on loan");
        if (m.borrowed >= m.limit) throw std::runtime_error(m.name + " reached the limit of " + std::to_string(m.limit));
        it.lend(member_id, today);
        ++m.borrowed;
        std::cout << std::format("  {} borrowed {} '{}', due day {}\n", m.name, it.type(), it.title(), it.due_day());
    }
    void give_back(int item_id, int today) {
        Item& it = find(item_id);
        Member& m = members_.at(it.borrower());
        int fine = it.give_back(today);
        --m.borrowed;
        fines_ += fine;
        std::cout << std::format("  {} returned '{}' on day {}: fine Rs. {}\n", m.name, it.title(), today, fine);
    }
    void search(const std::string& keyword) const {
        std::cout << "search '" << keyword << "':\n";
        for (const auto& it : items_)
            if (lower(it->title()).find(lower(keyword)) != std::string::npos)
                std::cout << std::format("  #{} [{}] {} {}\n", it->id(), it->type(), it->title(), it->details());
    }
    void overdue(int today) const {
        std::cout << "overdue on day " << today << ":\n";
        for (const auto& it : items_)
            if (it->on_loan() && today > it->due_day())
                std::cout << std::format("  '{}' with {} ({} days late)\n", it->title(), members_.at(it->borrower()).name, today - it->due_day());
    }
    int fines() const { return fines_; }
private:
    Item& find(int id) {
        auto it = std::find_if(items_.begin(), items_.end(), [id](const auto& p) { return p->id() == id; });
        if (it == items_.end()) throw std::out_of_range("no item #" + std::to_string(id));
        return **it;
    }
    static std::string lower(std::string s) {
        for (char& c : s) c = static_cast<char>(std::tolower(static_cast<unsigned char>(c)));
        return s;
    }
    std::vector<std::unique_ptr<Item>> items_;
    std::map<int, Member> members_;
    int next_id_ = 1, fines_ = 0;
};

int main() {
    Library lib;
    lib.add<Book>("Muna Madan", "Laxmi Prasad Devkota");
    lib.add<Book>("Palpasa Cafe", "Narayan Wagle");
    lib.add<DVD>("Kabaddi", 125);
    lib.add<Magazine>("Himal Khabarpatrika");
    lib.add<Book>("The C++ Programming Language", "Bjarne Stroustrup");
    lib.join(7, "Asha", 2);
    lib.join(8, "Ravi", 1);

    lib.search("c");
    std::cout << "day 1:\n";
    for (auto [member, item] : { std::pair{ 7, 1 }, { 7, 3 }, { 7, 5 }, { 8, 4 }, { 8, 1 }, { 8, 5 } }) {
        try { lib.borrow(member, item, 1); } catch (const std::exception& e) { std::cout << "  refused: " << e.what() << '\n'; }
    }
    lib.overdue(12);
    std::cout << "returns:\n";
    lib.give_back(3, 12);        // DVD due day 8 -> 4 days late x Rs. 20
    lib.give_back(1, 20);        // Book due day 22 -> on time
    lib.give_back(5, 30);        // Book due day 22 -> 8 days late x Rs. 5
    std::cout << "total fines collected: Rs. " << lib.fines() << '\n';
    return 0;
}

/* Output:
search 'c':
  #2 [Book] Palpasa Cafe by Narayan Wagle
  #5 [Book] The C++ Programming Language by Bjarne Stroustrup
day 1:
  Asha borrowed Book 'Muna Madan', due day 22
  Asha borrowed DVD 'Kabaddi', due day 8
  refused: Asha reached the limit of 2
  refused: Himal Khabarpatrika is reference only
  refused: Muna Madan is already on loan
  Ravi borrowed Book 'The C++ Programming Language', due day 22
overdue on day 12:
  'Kabaddi' with Asha (4 days late)
returns:
  Asha returned 'Kabaddi' on day 12: fine Rs. 80
  Asha returned 'Muna Madan' on day 20: fine Rs. 0
  Ravi returned 'The C++ Programming Language' on day 30: fine Rs. 40
total fines collected: Rs. 120
*/