Skip to content

Intermediate Project: A Small Library

Beginning of the lesson

Intermediate Project: A Small Library

Design and build one coherent, reusable statistics utility from scratch

Big Idea: A library is a small, well-designed unit of code that solves one problem so well that you never want to solve it again. In this capstone we combine everything from this course — classes, templates, the STL, RAII, references and const-correctness — to build a reusable Stats<T> class that collects numbers and computes statistics on them.
By the end you will be able to:
  • plan a small library's public API before writing a line of it,
  • wrap an STL container (std::vector<T>) so RAII handles all memory for you,
  • make the class a template so it works for int, double and more,
  • implement statistics with STL algorithms (std::accumulate, std::min_element, std::sort),
  • apply const-correctness and pass objects by const reference to avoid needless copies.

1. Plan first: what should the library do?

Think of a good library like a quality multi-tool. You do not carry ten separate gadgets; you carry one object whose buttons each do a clear job. Before writing code, we decide the public API — the set of operations a user can call — and keep everything else private.

Our target: a type Stats<T> that a user can fill with numbers, then ask for common statistics. The promised operations are:

  • add(value) and operator+= — put a number in;
  • count(), empty() — how many numbers so far;
  • sum(), mean(), min(), max() — the basics;
  • variance(), stddev(), median() — the spread.

The internal storage (a vector, an array, a file) is nobody's business but the class's. This separation — a clean surface over a hidden implementation — is called encapsulation, and it is the whole point of a library.

A good rule: the API is a promise. Once people rely on mean(), you can freely change how it is computed inside, but you must not change what it means outside.

Continue this lesson on YourAIZone

The full lesson has the complete explanation, worked examples, common mistakes, tests with instant checking and an AI tutor. Start right away as a guest, or create an account to keep your progress.

In the full lesson

  • The complete explanation
  • Worked examples
  • Common mistakes and how to avoid them
  • Test questions: 15
  • AI tutor that answers questions about the topic
  • Progress tracking for students, parents and teachers