Explain it simply
Explain it simply
Over the next three lessons you will build one small console program: a Student Manager that stores each student's name, roll number and marks. Part 1 builds the skeleton. Part 2 adds the features (add, list, search), and Part 3 makes the program survive bad input and remember its data after it closes.
Picture a school office. The register book holds the records, only one clerk is allowed to write in it, and requests arrive at a counter window. In our program the Student class is one record, StudentManager is the clerk who owns the register, and the menu loop is the counter window. Part 1 builds those three pieces and checks that they fit together.
Problem → Why → Solution
The problem: records anyone can scribble on
A first attempt usually makes every field public and keeps the list as a plain vector in main(). It runs, but nothing stops a bug, or a teammate, from writing nonsense into a record. In the draft below, one line sets Bo's marks to 940 instead of 94, and another adds a student with an empty name. The program accepts both without a word, and the class average is now meaningless.
The menu hides a second trap. It loops with while (true) and reads with std::cin >> choice, but never checks whether the read worked. If the user types a letter, the read fails, choice becomes 0, and every later read fails instantly, so the program prints "Invalid choice!" forever.
struct Student { // every field is public
std::string name;
int roll;
double marks;
};
int main() {
std::vector<Student> students;
students.push_back({"Bo", 2, 94});
students[0].marks = 940; // typo: nothing objects
students.push_back({"", 3, 70}); // empty name: accepted
int choice;
while (true) {
std::cin >> choice; // type a letter: the read fails every time
if (choice == 3) {
return 0;
}
std::cout << "Invalid choice!\n"; // printed forever
}
}Why can't the compiler help?
A struct with public fields promises that any code may write any value there. The compiler enforces exactly that promise, so 940 is legal. To enforce a rule such as "marks are 0 to 100", the rule has to live inside the type: private data plus member functions that check every change. The menu bug is similar: a stream remembers that a read failed, and it is your job to test that before you use the value.
Core concept: a class that keeps its rule, and one owner
A class is more than a bag of fields. Its real job is to keep an invariant: a rule that holds for every object from the moment it is built until it is destroyed. For a Student the rule is simple: marks are between 0 and 100. Part 1 enforces it in four steps.
1. Make the data private
name_, roll_ and marks_ live in the private section, so code outside the class cannot assign to them. The trailing underscore is a common naming habit that marks a member variable and keeps it apart from parameter names such as name.
2. Check in the constructor
The constructor uses a member initializer list, so each member is initialised once, directly, instead of being default-constructed and then assigned. marks_ is initialised from checkedMarks(marks), a private static helper that throws std::invalid_argument for any value outside 0 to 100. If it throws, no Student object comes into existence, so an invalid student can never be stored.
3. Read through const getters
getName(), getRoll() and getMarks() are marked const, a promise that they do not modify the object. That promise is what lets Part 2 call them through a const Student&. getName() returns const std::string&, so reading a name does not copy the string.
4. Change through one checked door
setMarks() calls the same checkedMarks() helper, so the rule lives in exactly one place. Without setMarks there would be no way to fix a typo; with a public field there would be no way to stop one.
The list needs an owner too. Instead of a loose std::vector<Student> in main() that has to be handed to every function, StudentManager keeps the vector as a private member and exposes operations such as add() and count(). Part 2 adds search and display to the same class and Part 3 adds saving, while main() never touches the vector directly.
Finally, the menu reads from a std::istream& instead of hard-coding std::cin. std::cin is an istream, and so is std::istringstream, which reads from a string. The demo feeds a scripted string of key presses so every run prints the same output; a real program simply passes std::cin. The condition while (in >> choice) is true only when a number was read successfully, so the loop stops when the input runs out or stops being numeric.
- Student: a record that guards its rule
- StudentManager: the owner of the vector
- Menu loop: read a choice, call the manager
- Bad value: exception, never stored
If a rule about the data matters, put it inside the class; then no caller can forget to apply it.
General pattern
class Thing {
public:
explicit Thing(Type value) : value_(checked(value)) {}
Type getValue() const { return value_; }
void setValue(Type value) { value_ = checked(value); }
private:
static Type checked(Type value); // throws when the rule is broken
Type value_;
};
class ThingManager { /* private: std::vector<Thing> items_; */ };Keep the data private, route both the constructor and the setter through one checking helper, make the read-only functions const, and let a manager class own the list as a private vector.
Part 1 code: the model and the menu skeleton
The file below holds the whole Part 1 program. main() first exercises the model directly: it adds two students, changes Chit's marks through setMarks(), and tries to build a student with 120 marks. Then it runs the menu with the scripted keys 1 2 7 3 standing in for a user at the keyboard. Options 1 and 2 are placeholders that Part 2 fills in.
To run it from the keyboard
Replace runMenu(keys, manager) with runMenu(std::cin, manager) in main(). Because runMenu accepts any istream, nothing else changes. The terminal already shows what you type, so you can drop the "> " echo line.
#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:
void add(const Student& student) { students_.push_back(student); }
std::size_t count() const { return students_.size(); }
private:
std::vector<Student> students_;
};
void runMenu(std::istream& in, StudentManager& manager) {
std::cout << "--- Student Manager ---\n"
<< "1. Add Student 2. Display All 3. Exit\n";
int choice = 0;
while (in >> choice) {
std::cout << "> " << choice << '\n'; // echo: scripted keys are not typed
switch (choice) {
case 1:
std::cout << "Add Student: coming in Part 2\n";
break;
case 2:
std::cout << "Display All: coming in Part 2\n";
break;
case 3:
std::cout << "Goodbye! " << manager.count() << " student(s) in memory.\n";
return;
default:
std::cout << "Invalid choice: " << choice << '\n';
}
}
std::cout << "Input ended before Exit.\n";
}
int main() {
StudentManager manager;
manager.add(Student("Aye", 1, 78.5));
manager.add(Student("Bo", 2, 91.0));
Student chit("Chit", 3, 64.0);
chit.setMarks(70.0);
std::cout << chit.getName() << " now has " << chit.getMarks() << " marks\n";
manager.add(chit);
try {
manager.add(Student("Daw", 4, 120.0));
} catch (const std::invalid_argument& e) {
std::cout << "Rejected Daw: " << e.what() << '\n';
}
std::istringstream keys("1 2 7 3"); // the keys a user would press
runMenu(keys, manager);
}Code breakdown
- Initializer list with a check
: name_(std::move(name)), roll_(roll), marks_(checkedMarks(marks)) {}Each member is initialised directly. std::move hands the name string over instead of copying it, and checkedMarks() runs before the object exists, so a bad value stops construction entirely.
- The one rule
throw std::invalid_argument("marks must be between 0 and 100");Daw's 120 reaches this line. The catch block in main() prints the message, and manager.add() is never called, which is why the final count is 3, not 4.
- const getter returning a reference
const std::string& getName() const { return name_; }The first const lets the caller read the name but not change it; the trailing const promises the function does not modify the object. Returning a reference avoids a copy.
- Private vector, public operation
void add(const Student& student) { students_.push_back(student); }This is the only way into the manager's list. In Part 2 the duplicate-roll check goes right here, and no caller has to change.
- Loop only while reads succeed
while (in >> choice) {in >> choice returns the stream, which tests true only if the read worked. When the script runs out or a letter arrives, the loop stops and prints "Input ended before Exit." instead of spinning forever.
- Scripted key presses
std::istringstream keys("1 2 7 3"); // the keys a user would pressAn istringstream reads a string exactly the way std::cin reads the keyboard. The 7 lands in the switch's default case, and the 3 prints Goodbye and returns.
Chit now has 70 marks
Rejected Daw: marks must be between 0 and 100
--- Student Manager ---
1. Add Student 2. Display All 3. Exit
> 1
Add Student: coming in Part 2
> 2
Display All: coming in Part 2
> 7
Invalid choice: 7
> 3
Goodbye! 3 student(s) in memory.- Read a number from the stream
- Echo it and pick a case
- Run the case, then loop again
Choice 3
Goodbye! ... then return
Read fails / input ends
Loop stops: no endless spin
Why not keep the vector in main()?
A vector<Student> students in main() works. But every new function then needs the vector as a parameter, and one that forgets the & receives a copy, so its changes vanish (Part 2 shows this bug for real). A rule about the whole list, such as "roll numbers are unique", would also have to be repeated wherever push_back is called.
Inside StudentManager, only the class's own member functions can change the list. Student guards the rule for one record; StudentManager guards the rules for the whole list.
In real projects
In real projects
School systems, clinic apps and a shop's stock program all use this pattern. A domain object (Student, Patient, Product) guards its own rules, and a repository or service class owns the collection. With that split, the user interface can move from a console menu to a GUI or a web API without touching the Student class.
Taking input as a std::istream& is also standard practice. Unit tests feed a command script through an istringstream and check the output, with nobody typing at a keyboard. Command-line tools use the same trick to read from a file or from the keyboard with one piece of code. And because validation sits in the constructor, data from a file, the network or the keyboard all pass through the same single door.
Common mistakes
Common mistakes
Making data public "for convenience"
Moving marks_ to public because writing getters feels tedious lets a line like s.marks_ = 120; compile and break the invariant. With marks_ private, g++ rejects it with error: 'double Student::marks_' is private within this context. That error is protecting you, not getting in your way.
Assigning in the constructor body without checking
Student(std::string n, int r, double m) { name = n; roll = r; marks = m; } default-constructs each member and then assigns it, and worse, it checks nothing. Use the initializer list and send the constructor through the same check as the setter; otherwise setMarks(120) is refused while Student("Daw", 4, 120) is happily accepted.
A while (true) menu that never checks the read
After std::cin >> choice fails, the stream stays in a failed state and every later read fails at once. Put the read in the loop condition (while (in >> choice)). Part 3 adds clear() and ignore() so the program can recover and carry on instead of stopping.
Mini challenge
Harden the model and add statistics
Extend the lesson's Student and StudentManager. The constructor must also reject an empty name and a roll number of 0 or below. Add hasPassed() to Student, and give the manager two functions that compute the pass count and the average marks.
- checkedName() and checkedRoll() throw std::invalid_argument with a clear message
- hasPassed() returns true when marks >= 40 (exactly 40 passes)
- averageMarks() returns 0.0 for an empty manager instead of dividing by zero
- main() prints the reason for every rejected student
// Start from the lesson's Student and StudentManager classes.
class Student {
public:
Student(std::string name, int roll, double marks); // TODO: check all three values
bool hasPassed() const; // TODO: true when marks >= 40
// ... keep the getters and setMarks() from the lesson
private:
static std::string checkedName(std::string name); // TODO: throw if empty
static int checkedRoll(int roll); // TODO: throw if <= 0
static double checkedMarks(double marks); // from the lesson
std::string name_;
int roll_;
double marks_;
};
class StudentManager {
public:
void add(const Student& student);
std::size_t count() const;
std::size_t countPassed() const; // TODO: count students who passed
double averageMarks() const; // TODO: 0.0 when there are no students
private:
std::vector<Student> students_;
};
int main() {
// TODO: print the stats of an empty manager first
// TODO: try to add ("Aye", 1, 78.5), ("", 2, 50), ("Bo", 0, 66),
// ("Chit", 3, 39.5) and ("Daw", 4, 40); print each rejection
// TODO: print count, countPassed() and averageMarks() with 2 decimals
}Expected: "0 students, average 0.00" for the empty manager, then two rejection lines (empty name, roll 0), and finally "Students: 3, passed: 2, average 52.67" (39.5 fails, 40 passes).
Show hint
Use all three helpers inside the initializer list, for example name_(checkedName(std::move(name))); members are initialised in the order they are declared in the class. For the average, sum into a double and divide by static_cast<double>(students_.size()).
Show solution
#include <format>
#include <iostream>
#include <stdexcept>
#include <string>
#include <utility>
#include <vector>
class Student {
public:
Student(std::string name, int roll, double marks)
: name_(checkedName(std::move(name))),
roll_(checkedRoll(roll)),
marks_(checkedMarks(marks)) {}
const std::string& getName() const { return name_; }
int getRoll() const { return roll_; }
double getMarks() const { return marks_; }
bool hasPassed() const { return marks_ >= 40.0; }
void setMarks(double marks) { marks_ = checkedMarks(marks); }
private:
static std::string checkedName(std::string name) {
if (name.empty()) {
throw std::invalid_argument("name must not be empty");
}
return name;
}
static int checkedRoll(int roll) {
if (roll <= 0) {
throw std::invalid_argument("roll must be positive");
}
return roll;
}
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:
void add(const Student& student) { students_.push_back(student); }
std::size_t count() const { return students_.size(); }
std::size_t countPassed() const {
std::size_t passed = 0;
for (const Student& s : students_) {
if (s.hasPassed()) {
++passed;
}
}
return passed;
}
double averageMarks() const {
if (students_.empty()) {
return 0.0; // no students: avoid dividing by zero
}
double total = 0.0;
for (const Student& s : students_) {
total += s.getMarks();
}
return total / static_cast<double>(students_.size());
}
private:
std::vector<Student> students_;
};
void tryAdd(StudentManager& manager, const std::string& name, int roll, double marks) {
try {
manager.add(Student(name, roll, marks));
} catch (const std::invalid_argument& e) {
std::cout << std::format("Rejected '{}' (roll {}): {}\n", name, roll, e.what());
}
}
int main() {
StudentManager manager;
std::cout << std::format("Empty: {} students, average {:.2f}\n",
manager.count(), manager.averageMarks());
tryAdd(manager, "Aye", 1, 78.5);
tryAdd(manager, "", 2, 50.0);
tryAdd(manager, "Bo", 0, 66.0);
tryAdd(manager, "Chit", 3, 39.5);
tryAdd(manager, "Daw", 4, 40.0);
std::cout << std::format("Students: {}, passed: {}, average {:.2f}\n",
manager.count(), manager.countPassed(),
manager.averageMarks());
}Quick quiz 1 / 3
Quick quiz 2 / 3
Quick quiz 3 / 3
What to remember
- A class guards an invariant: keep the data private and check every change
- Send the constructor and the setter through one checking helper
- Make getters const and return large members such as strings by const reference
- StudentManager owns the vector, and the menu reads from any std::istream
The Current ISO C++ Standard (C++23) — Standard C++ Foundation