Skip to main content

Lesson 2 of 7

Product Class Hierarchy Implementation

The `Product` base class and its three derived classes form the OOP core of the project. It exercises: const-correct public interface, Member Initialiser List, static counter, virtual destructor, pure virtual methods, `override`/`final`, operator overloading for comparison, and the full Rule of 5 (though Smart Pointers handle deletion automatically).

16 minBy Priygop Editorial TeamUpdated 2026Peer Reviewed & Verified

Product Base & Derived Classes - Complete Implementation

Product Base & Derived Classes - Complete Implementation
// ── include/exceptions.h ──────────────────────────────────────
#pragma once
#include <stdexcept>
#include <string>

class InventoryError : public std::runtime_error {
public:
    explicit InventoryError(const std::string& msg)
        : std::runtime_error(msg) {}
};

class ProductNotFound : public InventoryError {
    int id_;
public:
    explicit ProductNotFound(int id)
        : InventoryError("Product not found: #" + std::to_string(id))
        , id_(id) {}
    int id() const { return id_; }
};

class ValidationError : public InventoryError {
public:
    explicit ValidationError(const std::string& msg)
        : InventoryError("Validation: " + msg) {}
};

class PersistenceError : public InventoryError {
public:
    explicit PersistenceError(const std::string& msg)
        : InventoryError("Persistence: " + msg) {}
};

// ── include/product.h ─────────────────────────────────────────
#pragma once
#include <string>
#include <string_view>
#include <optional>
#include <chrono>
#include "exceptions.h"

class Product {
    static int next_id_;
    int         id_;
    std::string name_;
    double      price_;
    int         quantity_;

protected:
    // Protected helper for derived serialisation
    std::string base_csv() const;

public:
    Product(std::string name, double price, int qty);
    virtual ~Product() = default;

    // No copy (unique ownership via unique_ptr)
    Product(const Product&)            = delete;
    Product& operator=(const Product&) = delete;
    // Movable for factory returns
    Product(Product&&)            = default;
    Product& operator=(Product&&) = default;

    // ── Pure virtual interface ────────────────────────────────
    virtual std::string category()    const = 0;
    virtual std::string description() const = 0;
    virtual std::string serialize()   const = 0;

    // ── Virtual with default ──────────────────────────────────
    virtual void apply_discount(double pct) {
        if (pct < 0 || pct > 100) throw ValidationError("Discount must be 0-100");
        price_ *= (1.0 - pct / 100.0);
    }

    // ── Const accessors ───────────────────────────────────────
    int                  id()        const noexcept { return id_; }
    const std::string&   name()      const noexcept { return name_; }
    double               price()     const noexcept { return price_; }
    int                  quantity()  const noexcept { return quantity_; }

    // ── Mutators with validation ──────────────────────────────
    void set_name(std::string n) {
        if (n.empty()) throw ValidationError("Name cannot be empty");
        name_ = std::move(n);
    }
    void set_price(double p) {
        if (p < 0) throw ValidationError("Price cannot be negative");
        price_ = p;
    }
    void adjust_quantity(int delta) {
        if (quantity_ + delta < 0) throw ValidationError("Quantity would go negative");
        quantity_ += delta;
    }

    // ── Operator overloading ──────────────────────────────────
    bool operator< (const Product& o) const noexcept { return name_ <  o.name_; }
    bool operator==(const Product& o) const noexcept { return id_   == o.id_;   }

    friend std::ostream& operator<<(std::ostream& os, const Product& p);

    static int total_products() { return next_id_ - 1; }
};

class PhysicalProduct final : public Product {
    double      weight_kg_;
    std::string supplier_;
public:
    PhysicalProduct(std::string name, double price, int qty,
                    double weight_kg, std::string supplier)
        : Product(std::move(name), price, qty)
        , weight_kg_(weight_kg)
        , supplier_(std::move(supplier))
    {}

    std::string category()    const override { return "Physical"; }
    std::string description() const override;
    std::string serialize()   const override;
    double      weight()      const noexcept { return weight_kg_; }
    const std::string& supplier() const noexcept { return supplier_; }
};

class DigitalProduct final : public Product {
    std::string download_url_;
    std::string license_type_;
public:
    DigitalProduct(std::string name, double price, int qty,
                   std::string url, std::string license)
        : Product(std::move(name), price, qty)
        , download_url_(std::move(url))
        , license_type_(std::move(license))
    {
        // Digital products have unlimited "quantity" - often licences
    }

    std::string category()     const override { return "Digital"; }
    std::string description()  const override;
    std::string serialize()    const override;
    void apply_discount(double pct) override; // override to allow 100% promo
};

class PerishableProduct final : public Product {
    std::chrono::system_clock::time_point expiry_;
    std::string                           storage_requirements_;
public:
    PerishableProduct(std::string name, double price, int qty,
                      int days_until_expiry, std::string storage)
        : Product(std::move(name), price, qty)
        , expiry_(std::chrono::system_clock::now() +
                  std::chrono::hours(24 * days_until_expiry))
        , storage_requirements_(std::move(storage))
    {}

    std::string category()    const override { return "Perishable"; }
    std::string description() const override;
    std::string serialize()   const override;
    bool        expired()     const;  // checks vs now
    int         days_left()   const;  // days until expiry
};

Design Decisions

  • **Delete copy, default move** - since `unique_ptr` manages Product lifetime, Products should never be copied (two unique_ptrs to the same product would double-delete). Deleting copy is enforced at compile time. Move is defaulted for factory function returns.
  • `apply_discount()` is virtual with a default - Physical and Perishable products reuse the base implementation. Digital products override it to allow 100% discount (free promotional licenses). This is a good example of virtual function design: default behaviour in base, specialisation in derived.
  • **`final` on all three product types** - prevents accidental subclassing (e.g., `FrozenPerishable : PerishableProduct`). In a real system, this forces new product types to derive from `Product` directly and implement the full interface, keeping the hierarchy flat and predictable.

Tip

Tip

Practice Product Class Hierarchy Implementation in small, isolated examples before integrating into larger projects. Breaking concepts into small experiments builds genuine understanding faster than reading alone.

Diagram
Loading diagram…

Abstract Product Base with Virtual calculatePrice(), toCsv(), and Stream Overloading

Practice Task

Note

Practice Task - (1) Write a working example of Product Class Hierarchy Implementation from scratch without looking at notes. (2) Modify it to handle an edge case (empty input, null value, or error state). (3) Share your solution in the Priygop community for feedback.

Quick Quiz

Common Mistake

Warning

A common mistake with Product Class Hierarchy Implementation is skipping edge case testing - empty inputs, null values, and unexpected data types. Always validate boundary conditions to write robust, production-ready cpp code.

Key Takeaways

  • The `Product` base class and its three derived classes form the OOP core of the project.
  • *Delete copy, default move** - since `unique_ptr` manages Product lifetime, Products should never be copied (two unique_ptrs to the same product would double-delete). Deleting copy is enforced at compile time. Move is defaulted for factory function returns.
  • `apply_discount()` is virtual with a default - Physical and Perishable products reuse the base implementation. Digital products override it to allow 100% discount (free promotional licenses). This is a good example of virtual function design: default behaviour in base, specialisation in derived.
  • *`final` on all three product types** - prevents accidental subclassing (e.g., `FrozenPerishable : PerishableProduct`). In a real system, this forces new product types to derive from `Product` directly and implement the full interface, keeping the hierarchy flat and predictable.

Topics in This Module

0/7 done