Challenge: Enter and Leave
Write a class Room whose constructor prints enter NAME and whose destructor prints leave NAME. Read n names. Create the rooms nested: each one inside the one before, by having a recursive function create one Room and then call itself for the next name.
Input
n, then n names.
Output
For 2 names a b: enter a, enter b, leave b, leave a, one per line.
Example
Input
2 a b
Output
enter a enter b leave b leave a
Hints
The destructor's name is ~Room().
visit(names, i) makes Room r(names[i]); then calls visit(names, i + 1);
Each Room is destroyed when its visit() call ends, so they leave in reverse order.
Solution explanation
Each call keeps its Room alive until the deeper calls finish, so destructors run in reverse order – exactly how RAII cleans up.
Show solution
#include <iostream>
#include <string>
#include <vector>
using namespace std;
class Room {
string name;
public:
Room(string n) : name(n) { cout << "enter " << name << "\n"; }
~Room() { cout << "leave " << name << "\n"; }
};
void visit(const vector<string>& names, int i) {
if (i == static_cast<int>(names.size())) {
return;
}
Room r(names[i]);
visit(names, i + 1);
}
int main() {
int n;
cin >> n;
vector<string> names(n);
for (string& s : names) cin >> s;
visit(names, 0);
return 0;
}You can practice without logging in. Log in to save completion.
Save your progress
You're practising as a guest, so your progress won't be saved.
- Track every lab you complete
- Earn verifiable lab certificates
- See your progress in every module