C++
Putting it together
Combine the Quiz class with a console menu.
Putting it together
In the final lesson we add a reset() method to the Quiz class and complete the app. reset() zeroes the score so the quiz can be restarted.
All pieces are now together: the Question struct, addQuestion, run, getScore and reset methods. main creates a quiz, adds questions, runs it, prints the score and resets. This is a cumulative project example: each lesson was built on top of the previous one.
Project completed
You completed the project! Over five lessons you built a Quiz class step by step. This is a small example of real-world software development.
You first defined the data model (Question), then added methods for adding questions, running, scoring and resetting. Each lesson's starting code contained the previous solution, so the code grew cumulatively. This approach shows the power of breaking large projects into small steps.
Exercise Add the reset method to Quiz
Take the previous lesson's Quiz class. After getScore() add void reset() with body score = 0;. In main append << std::endl to the std::cout << "Score: " << quiz.getScore(); line, then add quiz.reset(); and std::cout << "Reset";.
Show example solution
#include <iostream>
#include <string>
#include <vector>
struct Question {
std::string text;
std::string answer;
};
class Quiz {
public:
std::vector<Question> questions;
int score = 0;
void addQuestion(std::string text, std::string answer) {
questions.push_back({text, answer});
}
void run() {
for (const auto& q : questions) {
std::cout << "Question: " << q.text << std::endl;
score++;
}
}
int getScore() {
return score;
}
void reset() {
score = 0;
}
};
int main() {
Quiz quiz;
quiz.addQuestion("Capital?", "Ankara");
quiz.addQuestion("Largest planet?", "Jupiter");
std::cout << "Quiz ready" << std::endl;
std::cout << quiz.questions.size() << " questions added" << std::endl;
quiz.run();
std::cout << "Score: " << quiz.getScore() << std::endl;
quiz.reset();
std::cout << "Reset";
return 0;
}
Test yourself
-
Match each method to its purpose
- addQuestion
- Add a question
- run
- Run the quiz
- getScore
- Read the score
- reset
- Reset
-
What does the reset() method do?
void reset() { score = 0; }
- Hides the methods
- Deletes the questions
- Closes the program
- Resets the score
Show answer
Resets the score — reset() sets the score variable to 0.
-
Complete the reset call
quiz.____();
Show answer
quiz.reset();
Next lesson: template<typename T>