Thuta Learning
C++
ExercisesProgrammingBeginner

Exercises: OOP & STL Challenge

C++Lesson 3540 min

What you'll walk away with

  • Write a class with private data and a checked constructor, and store its objects in a std::vector
  • Explain what & and * mean in a declaration and in an expression
  • Change an object through a pointer and check for nullptr before dereferencing
  • Tell apart a reference parameter that changes the caller's vector from a by-value one that works on a copy

Explain it simply

Explain it simply

This exercise set is tougher than the warm-up because it uses three topics from earlier chapters at once: classes and objects, std::vector, and pointers and references. Even if you understand each one alone, combining them gets confusing. The main reason is that the symbols & and * mean different things depending on where they appear.

Think of a library. A Book object is one book, a vector is a shelf, a pointer is a card saying where on the shelf to look, a reference is a second name for the same book, and passing by value is handing someone a photocopy. Notes written on a photocopy never appear in the real book, and that is exactly the central problem of this lesson.

Problem → Why → Solution

The problem: code that looks like it changes things and doesn't

The draft below contains two slips. The first is that doubleValues() takes the vector by value and also takes the loop variable int n by value. It works on two layers of copies, so nums in main() stays 1 2 3. This part compiles, and g++ -Wall gives just one warning: variable 'n' set but not used. It is a warning, not an error, so you notice it only if you read it.

The second slip is the last line. ptr = 100; was meant to change score, but it tries to give ptr itself a number. g++ refuses with error: invalid conversion from 'int' to 'int*'. Even after you fix that mistake, the first slip is still there.

draft.cpp
void doubleValues(std::vector<int> nums) {  // no &: the function gets a copy
    for (int n : nums) {                    // no &: n is a copy of each element
        n *= 2;
    }
}

int main() {
    std::vector<int> nums = {1, 2, 3};
    doubleValues(nums);
    for (int n : nums) {
        std::cout << n << ' ';  // prints 1 2 3: nothing was doubled
    }
    std::cout << '\n';

    int score = 90;
    int* ptr = &score;
    ptr = 100;  // meant: *ptr = 100
}

Why the difference?

In C++ the meaning of & depends on where it appears. Written in a type, as in std::vector<int>&, it means "another name for this object"; written in an expression, as in &score, it means "the address of score". * works the same way: in int* it declares a pointer type, and in *ptr it reaches the object the pointer points to. Every bug in this lesson comes from misreading one of these symbols.

Core concept: objects, addresses and names

All three tasks ask one question: which object is this code really touching? To answer it, you first have to know what & and * mean in each position.

What you writeWhat it means
int* pDeclaration: p is a pointer to an int
&scoreExpression: the address of score
*pExpression: the int p points to (read or write)
std::vector<int>& vDeclaration: another name for the caller's vector
const Book& bDeclaration: a read-only name, no copy

1. Task 1: a Book class that keeps its rule

title_ and price_ are private, and the constructor throws std::invalid_argument for a negative price. A vector<Book> stores a copy of each Book, so in push_back(Book("Misprint", -3.0)) the constructor throws while the argument is being built, push_back is never reached, and no bad book enters the vector. In the loop, read with const Book& b so that no book is copied.

2. Task 2: change a value through a pointer

After int* ptr = &score;, the statement *ptr += 10 changes the int that ptr points to, so score itself becomes 100. To change ptr itself, write ptr = &another, which changes what it points at. Dereferencing a pointer that holds nullptr is undefined behaviour, so check p == nullptr before using *p. Printing an address can differ from run to run, so for a test, compare pointers (ptr == &score) instead of printing them.

3. Task 3: change a vector through a reference

In void doubleValues(std::vector<int>& nums), the & makes nums refer to the caller's own vector. The loop also needs for (int& n : nums); only then do you change each element directly. Both places need the &, and with only one of them nothing changes. The example includes doubleCopy() as well, so the output shows directly what the by-value version does.

4. Check the edge cases

For an empty vector the loop never runs and nothing happens, which is correct. Doubling 0 and negative numbers is also correct. But doubling an int larger than 1,073,741,823 overflows a 32-bit int, which is signed overflow and undefined behaviour. The numbers here are small, so there is no problem in this exercise, but remember the limit in real code.

Mental model: which object is being touched?
  1. In a type & is a name, else an address
  2. *p reaches the object p points to
  3. Pass by value = copy; original unchanged
  4. Check for nullptr before dereferencing

For every line, ask whether it touches the original object or a copy. That one question catches every bug in this lesson.

General pattern

cpp
class Thing {                          // private data, checked constructor
public:
    Thing(Type a, Type b);             // throws when the rule is broken
    Type getA() const { return a_; }   // const: reading never changes it
private:
    Type a_, b_;
};

void change(std::vector<int>& v);          // &: works on the caller's vector
void show(const std::vector<Thing>& v);    // const &: read only, no copy
int* p = &x;  *p = 5;                      // & takes an address, * follows it

A class keeps its data private and checks it in the constructor. In a function parameter, & works on the caller's object and const & only reads it; with pointers, & takes an address and * follows that address to the object.

Reference solution: class, pointer and reference

The program below shows the three tasks in order. Task 1 first shows an empty vector, adds three books, and shows a book with a negative price being rejected. Task 2 does not print the address itself; it checks the claim with the comparison ptr == &score. Task 3 first calls doubleCopy() to show that nothing changes, and only then calls doubleValues().

oop_stl.cpp
#include <format>
#include <iostream>
#include <stdexcept>
#include <string>
#include <utility>
#include <vector>

// Task 1: a class that guards its own data.
class Book {
public:
    Book(std::string title, double price) : title_(std::move(title)), price_(price) {
        if (price_ < 0.0) {
            throw std::invalid_argument("price cannot be negative");
        }
    }

    const std::string& getTitle() const { return title_; }
    double getPrice() const { return price_; }

private:
    std::string title_;
    double price_;
};

void printBooks(const std::vector<Book>& books) {
    if (books.empty()) {
        std::cout << "  (no books)\n";
        return;
    }
    for (const Book& b : books) {
        const std::string price = std::format("${:.2f}", b.getPrice());
        std::cout << std::format("  {:<14}{:>8}\n", b.getTitle(), price);
    }
}

// Task 3: the & means "work on the caller's vector", not on a copy.
void doubleValues(std::vector<int>& nums) {
    for (int& n : nums) {
        n *= 2;
    }
}

void doubleCopy(std::vector<int> nums) {  // by value: only the copy changes
    for (int& n : nums) {
        n *= 2;
    }
}

void printInts(const std::string& label, const std::vector<int>& nums) {
    std::cout << "  " << label << ":";
    if (nums.empty()) {
        std::cout << " (empty)";
    }
    for (int n : nums) {
        std::cout << ' ' << n;
    }
    std::cout << '\n';
}

int main() {
    std::cout << "Task 1\n";
    std::vector<Book> books;
    printBooks(books);
    books.push_back(Book("C++ Basics", 8.5));
    books.push_back(Book("STL Guide", 12.0));
    books.push_back(Book("OOP in Depth", 15.75));
    try {
        books.push_back(Book("Misprint", -3.0));
    } catch (const std::invalid_argument& e) {
        std::cout << "  rejected Misprint: " << e.what() << '\n';
    }
    printBooks(books);

    std::cout << "Task 2\n";
    int score = 90;
    int* ptr = &score;
    std::cout << std::boolalpha << "  ptr holds the address of score: "
              << (ptr == &score) << '\n';
    *ptr += 10;  // change the int that ptr points to
    std::cout << "  *ptr = " << *ptr << ", score = " << score << '\n';
    int* nowhere = nullptr;
    if (nowhere == nullptr) {
        std::cout << "  nowhere is null, so it must not be dereferenced\n";
    }

    std::cout << "Task 3\n";
    std::vector<int> nums = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
    doubleCopy(nums);
    printInts("after doubleCopy", nums);
    doubleValues(nums);
    printInts("after doubleValues", nums);
    std::vector<int> mixed = {-3, 0, 4};
    doubleValues(mixed);
    printInts("negatives and zero", mixed);
    std::vector<int> empty;
    doubleValues(empty);
    printInts("empty vector", empty);
}

Code breakdown

  1. Constructor with an initializer listBook(std::string title, double price) : title_(std::move(title)), price_(price) {

    Both members are initialised directly through the initializer list. The if (price_ < 0.0) in the body then checks and throws, so a bad Book can never exist.

  2. The rule that rejects bad datathrow std::invalid_argument("price cannot be negative");

    Misprint with -3.0 reaches this line. The catch in main() prints "rejected Misprint: price cannot be negative" and carries on, so the final list has only three books.

  3. Reference loop variablefor (int& n : nums) {

    int& n is another name for each element in the vector, so n *= 2 changes the vector itself. doubleValues has this & and also an & on the parameter, so the change reaches the caller.

  4. A parameter that copiesvoid doubleCopy(std::vector<int> nums) { // by value: only the copy changes

    Here the loop uses int&, but nums itself is a copy. The change stays in the copy and disappears when the function returns, so the "after doubleCopy" line still shows 1 to 10.

  5. Write through the pointer*ptr += 10; // change the int that ptr points to

    ptr points at score, so *ptr behaves like another name for score. That is why the output shows both *ptr = 100 and score = 100.

  6. A pointer that points nowhereint* nowhere = nullptr;

    nullptr means "points at nothing". This pointer must never be dereferenced with *nowhere; the program tests it with if (nowhere == nullptr) first.

You should see
Task 1
  (no books)
  rejected Misprint: price cannot be negative
  C++ Basics       $8.50
  STL Guide       $12.00
  OOP in Depth    $15.75
Task 2
  ptr holds the address of score: true
  *ptr = 100, score = 100
  nowhere is null, so it must not be dereferenced
Task 3
  after doubleCopy: 1 2 3 4 5 6 7 8 9 10
  after doubleValues: 2 4 6 8 10 12 14 16 18 20
  negatives and zero: -6 0 8
  empty vector: (empty)

Why return a pointer and not a reference?

Consider cheapest() from the challenge. An empty library has no cheapest book. A reference must always refer to an object, so it cannot express "nothing". A pointer can say it with nullptr, or the function can return a std::optional<Book>, which is a copy.

A returned pointer points at an element inside the vector, so it can stop being valid when the vector changes: push_back may reallocate, and a sort moves elements around, so another book may now sit where that element was. Use the result immediately and read it before changing the vector.

In real projects

In real projects

Inventory, library and shop apps use this shape every day. A domain class (Book, Product) keeps its own rules and a collection class owns the vector. APIs use const & for every read-only function and a non-const & only where a function must change data, so reading the signatures tells you which functions may modify something.

Today pointers are mostly used as non-owning "look here" handles, and you meet them unavoidably when talking to C libraries. Keeping prices in a double is fine for an exercise, but real money code usually stores whole units such as cents, to avoid rounding trouble. Breaking price ties by title is normal too, so the same screen shows the same order on every run.

Common mistakes

Common mistakes

Changing ptr when you meant *ptr

ptr = 100; makes g++ report error: invalid conversion from 'int' to 'int*' [-fpermissive]. ptr = ptr + 10; compiles, but it points ten ints further along and leaves score unchanged, and reading through that pointer is undefined behaviour. To change the value, write *ptr += 10.

Forgetting the & in a range-for

for (int n : nums) n *= 2; doubles a copy of each element and leaves the vector alone. g++ -Wall often prints warning: variable 'n' set but not used, so do not skip the warnings. Use int& n to change the vector and const int& n to read it.

A getter that is not const

Writing std::string getTitle() { ... } without const and calling b.getTitle() on a const Book& b makes g++ report error: passing 'const Book' as 'this' argument discards qualifiers [-fpermissive]. Only const member functions can be called through a const Book&, so mark every getter const.

Not checking for nullptr

A function like cheapest() returns nullptr for an empty library. Calling ->getTitle() on the result without a check is undefined behaviour, and such a bug rarely shows up while you test with data present; it appears when the first real user hits the empty case. After every call that returns a pointer, test it with if (p) or if (p != nullptr).

Mini challenge

Build a Library class

Using the lesson's Book class, write a Library class. Store the books in a private vector and provide: the cheapest book as a pointer, the total value, sorting by price, and a filter for books under a limit. Test an empty library, two books with the same price, and a filter that matches nothing.

  • cheapest() returns nullptr for an empty library, and the first-added book when prices tie
  • totalValue() returns 0.0 for an empty library; start std::accumulate with 0.0, not 0
  • sortByPrice() sorts by ascending price and breaks ties alphabetically by title
  • under(limit) returns copies of the books priced strictly below the limit
  • all() returns a const vector<Book>& and never copies the vector
challenge.cpp
// Reuse the Book class (private title and price, checked constructor).

class Library {
public:
    void add(const Book& book);                   // TODO: store a copy
    const Book* cheapest() const;                 // TODO: nullptr when empty;
                                                  //       first of equal prices wins
    double totalValue() const;                    // TODO: 0.0 when empty
    void sortByPrice();                           // TODO: price ascending, then title
    std::vector<Book> under(double limit) const;  // TODO: price strictly below limit
    const std::vector<Book>& all() const;         // TODO: read-only view, no copy

private:
    std::vector<Book> books_;
};

int main() {
    // TODO: ask an empty library for cheapest() and totalValue()
    // TODO: add STL Guide 12.00, Pointers 101 8.50, C++ Basics 8.50, OOP in Depth 15.75
    // TODO: print the cheapest title and the total with 2 decimals
    // TODO: sort, then print all books, then under(12.0) and under(5.0)
}

Expected: "cheapest = none, total $0.00" for the empty library, then "Cheapest: Pointers 101", "Total value: $44.75", the four books sorted by price (C++ Basics before Pointers 101), "Under $12.00 (2)" and "Under $5.00 (0)".

Show hint

For cheapest(), use std::min_element with a comparator and return &*it; min_element returns the first of several equal minimums. In std::accumulate(begin, end, 0.0, lambda), writing 0 instead of 0.0 stores the running sum as an int and drops the fractions: 44.75 would become 43. For under(), std::copy_if with std::back_inserter works.

Show solution
challenge.cpp
#include <algorithm>
#include <format>
#include <iostream>
#include <iterator>
#include <numeric>
#include <stdexcept>
#include <string>
#include <utility>
#include <vector>

class Book {
public:
    Book(std::string title, double price) : title_(std::move(title)), price_(price) {
        if (price_ < 0.0) {
            throw std::invalid_argument("price cannot be negative");
        }
    }

    const std::string& getTitle() const { return title_; }
    double getPrice() const { return price_; }

private:
    std::string title_;
    double price_;
};

class Library {
public:
    void add(const Book& book) { books_.push_back(book); }

    // nullptr when the library is empty; on a tie the book added first wins.
    const Book* cheapest() const {
        if (books_.empty()) {
            return nullptr;
        }
        auto it = std::min_element(books_.begin(), books_.end(),
                                   [](const Book& a, const Book& b) {
                                       return a.getPrice() < b.getPrice();
                                   });
        return &*it;
    }

    double totalValue() const {
        // 0.0, not 0: the start value decides the type of the running sum
        return std::accumulate(books_.begin(), books_.end(), 0.0,
                               [](double sum, const Book& b) {
                                   return sum + b.getPrice();
                               });
    }

    void sortByPrice() {
        std::sort(books_.begin(), books_.end(), [](const Book& a, const Book& b) {
            if (a.getPrice() != b.getPrice()) {
                return a.getPrice() < b.getPrice();
            }
            return a.getTitle() < b.getTitle();  // same price: alphabetical
        });
    }

    std::vector<Book> under(double limit) const {
        std::vector<Book> result;
        std::copy_if(books_.begin(), books_.end(), std::back_inserter(result),
                     [limit](const Book& b) { return b.getPrice() < limit; });
        return result;
    }

    const std::vector<Book>& all() const { return books_; }

private:
    std::vector<Book> books_;
};

void printBooks(const std::string& label, const std::vector<Book>& books) {
    std::cout << label << " (" << books.size() << ")\n";
    for (const Book& b : books) {
        std::cout << std::format("  {:<14}{:>8}\n", b.getTitle(),
                                 std::format("${:.2f}", b.getPrice()));
    }
}

int main() {
    Library library;
    const Book* first = library.cheapest();
    std::cout << "Empty library: cheapest = " << (first ? first->getTitle() : "none")
              << std::format(", total ${:.2f}\n", library.totalValue());

    library.add(Book("STL Guide", 12.0));
    library.add(Book("Pointers 101", 8.5));
    library.add(Book("C++ Basics", 8.5));
    library.add(Book("OOP in Depth", 15.75));

    const Book* cheap = library.cheapest();
    std::cout << "Cheapest: " << cheap->getTitle() << '\n';
    std::cout << std::format("Total value: ${:.2f}\n", library.totalValue());

    library.sortByPrice();
    printBooks("Sorted by price", library.all());
    printBooks("Under $12.00", library.under(12.0));
    printBooks("Under $5.00", library.under(5.0));
}

Quick quiz 1 / 3

After int score = 90; int* p = &score; *p += 10;, which statement is true?

Quick quiz 2 / 3

After calling void f(std::vector<int> v) { for (int& x : v) x *= 2; } with nums = {1, 2, 3}, what is the caller's nums?

Quick quiz 3 / 3

In a library holding [STL Guide 12.00, Pointers 101 8.50, C++ Basics 8.50, OOP in Depth 15.75], which title does a std::min_element-based cheapest() point to?

What to remember

  • & and * change meaning with position: & in a type is a name, & in an expression is an address, and *p is the pointed-to object
  • A parameter taken by value changes only a copy, and a range-for needs & before it can change the elements
  • Check for nullptr before dereferencing, and do not trust an old pointer after the vector changes
  • A rule checked in the constructor keeps bad objects out of the vector

The Current ISO C++ Standard (C++23) — Standard C++ Foundation

Updated on

Progress is saved only in this browser on this device. It isn't synced to other devices.

Report a problem with this lessonOpens your email app with this lesson's address filled in — nothing is sent until you send it.

Exercises: OOP & STL Challenge | Thuta Learning