Building a Console Project
Snapping functions, a class, and the STL into one real program
- combine a class, a std::vector, and functions into one working program,
- read a complete C++ console program and predict its output,
- explain how
main()ties all the pieces together.
1. The plan: a tiny task manager
We will build a small program that keeps a to-do list. It stores several tasks, lets us mark one as finished, prints the list, and counts how many are done. Here is what it will print when we run it:
--- My Tasks ---
1. [x] Read a book
2. [ ] Walk the dog
3. [ ] Write C++ code
Done: 1 / 3
To get there we need three building blocks: a class for one task, an STL vector to hold many tasks, and functions to do the work. Let's build them one at a time.
2. Step 1 — a class as a blueprint
A class is a blueprint. It bundles data (what a thing knows) with behaviour (what a thing can do). Our Task knows a title and whether it is done, and it can markDone() itself.
class Task {
public:
std::string title; // data
bool done; // data
Task(std::string t) { // constructor: builds a Task
title = t;
done = false;
}
void markDone() { // behaviour (a method)
done = true;
}
std::string status() const {
return done ? "[x]" : "[ ]";
}
};
- The constructor
Task(std::string t)runs when a task is created and fills in the starting values. markDone()andstatus()are methods — functions that belong to the class.- Don't forget the semicolon after the closing brace:
};