Thuta Learning
C++
ProjectsProgrammingBeginner

Mini Project: Student Manager - Part 2

C++Lesson 3240 min

What you'll walk away with

  • Choose a parameter type by asking whether a function needs the caller's object, a read-only view or its own copy
  • Write a search that can fail as a pointer-or-nullptr return that stops at the first match
  • Mark member functions const so they can be called through a const StudentManager&
  • Print an aligned table with std::format width specifiers

Explain it simply

Explain it simply

After Part 1 there is a clerk (StudentManager) who owns the register, but the clerk cannot do anything yet. Part 2 teaches three jobs: enrol a new student, read out the whole list, and look someone up by roll number.

Every time you hand the clerk a job, you decide whether to give the original register, a look-but-don't-touch view, or a photocopy. Enrolling a student on a photocopy never reaches the real register. In C++ those three choices are a reference (&), a const reference (const &) and pass by value, and most bugs in this lesson come from picking the wrong one.

Problem → Why → Solution

The problem: two helpers that compile and are wrong

Both functions in the draft below compile without a warning. addStudent() prints "Student added!", yet on the next line the caller's vector still has size 0. The parameter has no &, so the function receives a copy of the vector, adds to the copy, and the copy disappears when the function returns.

searchByRoll() finds roll 2, prints "Found: Bo" and then also prints "Student not found." There is no return after the match, so the loop keeps going and the line after the loop always runs. Mixing the searching with the printing makes this bug easy to write.

draft_helpers.cpp
// Draft helpers: both compile, both are wrong.
void addStudent(std::vector<Student> students, const Student& s) {
    students.push_back(s);  // pushes into a copy
    std::cout << "Student added!\n";
}

void searchByRoll(const std::vector<Student>& students, int roll) {
    for (const Student& s : students) {
        if (s.getRoll() == roll) {
            std::cout << "Found: " << s.getName() << '\n';
        }  // no return: the loop keeps going
    }
    std::cout << "Student not found.\n";
}

int main() {
    std::vector<Student> students;
    addStudent(students, Student("Aye", 1, 78.5));
    std::cout << students.size() << '\n';  // 0

    students.push_back(Student("Bo", 2, 91.0));
    searchByRoll(students, 2);  // prints Found AND not found
}

Why does this happen?

C++ passes parameters by value unless you say otherwise, so each function gets its own copy. Copying a vector copies every element, which is slow and also throws away any changes. The search bug is a control-flow problem: unless "found it" leaves the function immediately with a return, the function keeps running.

Core concept: original, view or copy

Part 2 turns the placeholders into real features. All three live in StudentManager, and all three depend on one question: does this code need the original object, a read-only view of it, or its own copy? C++ makes you say which, and that choice decides both correctness and speed.

Parameter formWhat the function getsUse it when
Student sIts own copyIt keeps or edits a private copy
Student& sThe caller's object, writableIt must change the caller's object
const Student& sThe caller's object, read-onlyIt only reads (the common case)

add(): reject duplicates, then push_back

add() takes const Student& because it only reads its argument; push_back then stores the vector's own copy. Before storing, add() calls findByRoll() and returns false if the roll number is taken, so the list rule "roll numbers are unique" lives in one place. Returning bool lets the caller decide how to report the problem.

findByRoll(): return a pointer or nullptr

A search can fail, so it needs a way to say "nothing found". Returning const Student* does that: the address of the matching element, or nullptr. The loop returns the moment it finds a match, so it never keeps scanning or reports twice. The function only reads, so it is marked const, and the pointer points to const, so callers cannot edit a student through it.

displayAll(): const, empty case first

displayAll() handles the empty list first and returns early, then prints a header and one row per student with std::format. Width specifiers such as {:>4} and {:<8} keep the columns lined up, and {:>6.1f} prints marks with one decimal place.

Free functions for input

addFromInput() and searchFromInput() read the values for one command from the stream and call the manager. They take StudentManager& or const StudentManager& depending on whether they change it. searchFromInput can only call const member functions, which is exactly why findByRoll must be const.

Mental model: original, view or copy?
  1. Changes the caller's object? Use &
  2. Only reads it? Use const &
  3. Search may fail? Return pointer or null
  4. Found it? Return at once

Default to const & for objects you only read, and drop the const only when the function really must change the original.

General pattern

cpp
class Manager {
public:
    bool add(const Item& item);       // reads the argument, stores a copy
    const Item* find(Key key) const;  // nullptr when nothing matches
    void show() const;                // read-only member function
private:
    std::vector<Item> items_;
};

void readCommand(std::istream& in, Manager& manager);       // may change it
void reportOnly(std::istream& in, const Manager& manager);  // only reads it

Operations that change the list are non-const, read-only ones are const, a search that can fail returns a pointer, and functions that receive the Manager pick & or const & on purpose.

Part 2 code: add, display and search

Student is exactly as in Part 1. StudentManager gains add() with a duplicate check, findByRoll() and displayAll(), and the menu gains option 4 for search. The script asks for the list while it is still empty, adds three students (the third reuses roll 1), shows the list, then searches for one roll that exists and one that does not. The values after option 1, such as "Aye 1 78.5", are read by addFromInput().

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

class Student {
public:
    Student(std::string name, int roll, double marks)
        : name_(std::move(name)), roll_(roll), marks_(checkedMarks(marks)) {}

    const std::string& getName() const { return name_; }
    int getRoll() const { return roll_; }
    double getMarks() const { return marks_; }

    void setMarks(double marks) { marks_ = checkedMarks(marks); }

private:
    static double checkedMarks(double marks) {
        if (marks < 0.0 || marks > 100.0) {
            throw std::invalid_argument("marks must be between 0 and 100");
        }
        return marks;
    }

    std::string name_;
    int roll_;
    double marks_;
};

class StudentManager {
public:
    bool add(const Student& student) {
        if (findByRoll(student.getRoll()) != nullptr) {
            return false;  // roll numbers must stay unique
        }
        students_.push_back(student);
        return true;
    }

    const Student* findByRoll(int roll) const {
        for (const Student& s : students_) {
            if (s.getRoll() == roll) {
                return &s;  // first match: stop searching
            }
        }
        return nullptr;
    }

    void displayAll() const {
        if (students_.empty()) {
            std::cout << "No students yet.\n";
            return;
        }
        std::cout << "Roll  Name     Marks\n";
        for (const Student& s : students_) {
            std::cout << std::format("{:>4}  {:<8}{:>6.1f}\n",
                                     s.getRoll(), s.getName(), s.getMarks());
        }
    }

    std::size_t count() const { return students_.size(); }

private:
    std::vector<Student> students_;
};

void addFromInput(std::istream& in, StudentManager& manager) {
    std::string name;
    int roll = 0;
    double marks = 0.0;
    in >> name >> roll >> marks;
    if (manager.add(Student(name, roll, marks))) {
        std::cout << "Added " << name << '\n';
    } else {
        std::cout << "Roll " << roll << " already exists\n";
    }
}

void searchFromInput(std::istream& in, const StudentManager& manager) {
    int roll = 0;
    in >> roll;
    if (const Student* found = manager.findByRoll(roll)) {
        std::cout << std::format("Found: {} ({:.1f})\n",
                                 found->getName(), found->getMarks());
    } else {
        std::cout << "Roll " << roll << " not found\n";
    }
}

void runMenu(std::istream& in, StudentManager& manager) {
    int choice = 0;
    while (in >> choice) {
        std::cout << "> " << choice << '\n';
        switch (choice) {
        case 1: addFromInput(in, manager); break;
        case 2: manager.displayAll(); break;
        case 3: std::cout << "Goodbye!\n"; return;
        case 4: searchFromInput(in, manager); break;
        default: std::cout << "Invalid choice: " << choice << '\n';
        }
    }
}

int main() {
    StudentManager manager;
    std::istringstream keys(
        "2\n"
        "1 Aye 1 78.5\n"
        "1 Bo 2 91\n"
        "1 Chit 1 55\n"
        "2\n"
        "4 2\n"
        "4 9\n"
        "3\n");
    runMenu(keys, manager);
}

Code breakdown

  1. The list rule in one placeif (findByRoll(student.getRoll()) != nullptr) {

    Chit's roll 1 is caught here: add() returns false, nothing enters the vector, and the caller prints "Roll 1 already exists".

  2. Read-only loop variablefor (const Student& s : students_) {

    const Student& gives each element by reference without copying it, and const stops the loop body from modifying it.

  3. Stop at the first matchreturn &s; // first match: stop searching

    &s is the address of the element inside the vector. return leaves at once, so the final return nullptr is only reached when nothing matched.

  4. Aligned columnsstd::cout << std::format("{:>4} {:<8}{:>6.1f}\n",

    The roll is right-aligned in width 4, the name left-aligned in width 8, and the marks right-aligned in width 6 with one decimal, which is why 91 shows as 91.0 in a straight column.

  5. Pointer declared in the ifif (const Student* found = manager.findByRoll(roll)) {

    found is declared in the condition and tests true when it is not nullptr. Its scope ends with the if/else, so nobody can hold on to a pointer into a vector that may change later.

You should see
> 2
No students yet.
> 1
Added Aye
> 1
Added Bo
> 1
Roll 1 already exists
> 2
Roll  Name     Marks
   1  Aye       78.5
   2  Bo        91.0
> 4
Found: Bo (91.0)
> 4
Roll 9 not found
> 3
Goodbye!

A pointer into a vector does not last forever

findByRoll() returns the address of an element inside students_. That address is valid only until the vector changes. When push_back needs more room, the vector allocates a bigger block, moves every element there and frees the old block, so a pointer saved earlier now points at freed memory. Reading through it is undefined behaviour: it may print the right name, print garbage, or crash.

The rule for this project: use the pointer immediately, as searchFromInput() does, and never keep it across an add() or a removal. If a caller really needs to keep the result, return a copy instead, for example a std::optional<Student> (C++17), which holds either one Student or nothing.

In real projects

In real projects

Every real app has these three operations: insert a record, list records, find one by ID. The duplicate check in add() mirrors a database UNIQUE constraint: the database itself refuses a second row with the same ID, and the app turns that error into a message the user understands. Returning "not found" as nullptr, std::optional or, in a web API, a 404 response rather than an exception is also normal, because a missing record is an ordinary outcome, not a failure.

Const-correctness matters in team work too. If a reporting module only accepts const StudentManager&, a reviewer knows it cannot modify the data without reading every line, because the compiler guarantees it.

Common mistakes

Common mistakes

Passing the vector by value

void addStudent(std::vector<Student> students, ...) adds to a copy, so the caller's list never changes. In a read-only function the result is correct, but every call copies every student. Use & to change the list and const & to read it.

No return after the match

Printing "Found" inside the loop without returning lets the loop continue, and the "not found" line after it runs too. If the search function only returns a result and the caller does the printing, this bug becomes hard to write.

Forgetting const on read-only members

Writing displayAll() without const and calling it through a const StudentManager& makes g++ report error: passing 'const StudentManager' as 'this' argument discards qualifiers. Removing the const from the caller is the wrong fix; add const to the member function.

Storing the pointer from findByRoll

Saving the pointer in a variable and using it after more students are added can leave it dangling, because the vector may have reallocated in between. Use it immediately or keep a copy.

Mini challenge

Add search by name and removal

Add two operations to StudentManager. Names can repeat, so findByName() must return every match as a copy. removeByRoll() deletes the student with a given roll and reports whether there was one. Wire both to menu options 6 and 7 (5 is kept free for the sort in Part 3).

  • findByName() is a const member function returning std::vector<Student> (empty when nothing matches)
  • removeByRoll() returns true if it erased a student and false if the roll was not there
  • Remove the same roll twice and show that the second attempt reports "not found"
  • Test a name with two matches and a name with none
challenge.cpp
// Student is unchanged. Add two operations to the lesson's StudentManager.

class StudentManager {
public:
    // ... add(), findByRoll(), displayAll() and count() from the lesson

    // TODO: return every student whose name equals `name`, as copies.
    //       An empty vector means "no match".
    std::vector<Student> findByName(const std::string& name) const;

    // TODO: erase the student with this roll; return false if there was none.
    bool removeByRoll(int roll);

private:
    std::vector<Student> students_;
};

void runMenu(std::istream& in, StudentManager& manager) {
    // TODO: case 6 reads a name, prints "> 6 <name>: N match(es)",
    //       then one "  roll R (M)" line per match
    // TODO: case 7 reads a roll, prints "> 7 <roll>: removed" or "... not found"
    // TODO: case 3 prints how many students are left and returns
}

int main() {
    // TODO: add Aye (1, 78.5), Bo (2, 91) and a second Aye (3, 64), then run
    //       the keys "6 Aye\n6 Zaw\n7 2\n7 2\n6 Bo\n3\n"
}

Expected: Two matches for "Aye" (rolls 1 and 3), zero for "Zaw", roll 2 "removed" the first time and "not found" the second, zero matches for "Bo" after removal, and 2 students left at the end.

Show hint

For findByName(), create an empty vector and push_back each matching student. For removeByRoll(), C++20's std::erase_if(students_, lambda) returns how many elements it removed, so compare that with 0.

Show solution
challenge.cpp
#include <format>
#include <iostream>
#include <sstream>
#include <stdexcept>
#include <string>
#include <utility>
#include <vector>

class Student {
public:
    Student(std::string name, int roll, double marks)
        : name_(std::move(name)), roll_(roll), marks_(checkedMarks(marks)) {}

    const std::string& getName() const { return name_; }
    int getRoll() const { return roll_; }
    double getMarks() const { return marks_; }

    void setMarks(double marks) { marks_ = checkedMarks(marks); }

private:
    static double checkedMarks(double marks) {
        if (marks < 0.0 || marks > 100.0) {
            throw std::invalid_argument("marks must be between 0 and 100");
        }
        return marks;
    }

    std::string name_;
    int roll_;
    double marks_;
};

class StudentManager {
public:
    bool add(const Student& student) {
        for (const Student& s : students_) {
            if (s.getRoll() == student.getRoll()) {
                return false;
            }
        }
        students_.push_back(student);
        return true;
    }

    // Names are not unique, so return every match as a copy (safe to keep).
    std::vector<Student> findByName(const std::string& name) const {
        std::vector<Student> matches;
        for (const Student& s : students_) {
            if (s.getName() == name) {
                matches.push_back(s);
            }
        }
        return matches;
    }

    bool removeByRoll(int roll) {
        auto removed = std::erase_if(students_, [roll](const Student& s) {
            return s.getRoll() == roll;
        });
        return removed > 0;
    }

    std::size_t count() const { return students_.size(); }

private:
    std::vector<Student> students_;
};

void runMenu(std::istream& in, StudentManager& manager) {
    int choice = 0;
    while (in >> choice) {
        switch (choice) {
        case 6: {
            std::string name;
            in >> name;
            const std::vector<Student> matches = manager.findByName(name);
            std::cout << std::format("> 6 {}: {} match(es)\n", name, matches.size());
            for (const Student& s : matches) {
                std::cout << std::format("  roll {} ({:.1f})\n",
                                         s.getRoll(), s.getMarks());
            }
            break;
        }
        case 7: {
            int roll = 0;
            in >> roll;
            const bool removed = manager.removeByRoll(roll);
            std::cout << std::format("> 7 {}: {}\n", roll,
                                     removed ? "removed" : "not found");
            break;
        }
        case 3:
            std::cout << "Goodbye! " << manager.count() << " student(s) left.\n";
            return;
        default:
            std::cout << "Invalid choice: " << choice << '\n';
        }
    }
}

int main() {
    StudentManager manager;
    manager.add(Student("Aye", 1, 78.5));
    manager.add(Student("Bo", 2, 91.0));
    manager.add(Student("Aye", 3, 64.0));

    std::istringstream keys("6 Aye\n6 Zaw\n7 2\n7 2\n6 Bo\n3\n");
    runMenu(keys, manager);
}

Quick quiz 1 / 3

After calling void addStudent(std::vector<Student> students, const Student& s) { students.push_back(s); } on an empty vector, what is the caller's size()?

Quick quiz 2 / 3

With the script "1 Aye 1 78.5\n1 Bo 1 60\n4 1\n", what does option 4 print?

Quick quiz 3 / 3

You keep const Student* p = manager.findByRoll(1); then add three more students and read p->getName(). What is the risk?

What to remember

  • Pass & to change an object, const & to read it, and by value only when you really want a copy
  • The duplicate-roll check inside add() keeps the list rule in one place
  • A search that can fail returns a pointer or nullptr and returns at the first match
  • Mark read-only member functions const, and never hold a pointer into a vector for long

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.

Mini Project: Student Manager - Part 2 | Thuta Learning