An object that contains other objects is built from the inside out, and taken apart from the outside in.
What to build
A Room class with two Part members, whose constructors and destructors report when they run.
Requirements
Partprintspart NAME madewhen built andpart NAME removedwhen destroyed.Roomholds twoPartmembers, declared first and second, and printsroom NAME madeandroom NAME closed.- Build the parts in
Room's member initializer list. - Keep
mainas it is.
Input
One line with three words: the room's name, the first part's name and the second part's name.
Output
Seven lines, in the order the constructors, main and the destructors print them.
Constraints
Each name is one word.
Example
Input:
Kitchen sink oven
Output:
part sink made
part oven made
room Kitchen made
in use
room Kitchen closed
part oven removed
part sink removed
Why it works
C++ builds members before the constructor body so that the body can use them, in their declared order. Destruction mirrors construction exactly, so the members outlive the destructor body that might still need them.
Examples
Kitchen sink oven
part sink made part oven made room Kitchen made in use room Kitchen closed part oven removed part sink removed
Lab desk lamp
part desk made part lamp made room Lab made in use room Lab closed part lamp removed part desk removed
Hints
Hint 1
Member objects are built before the body of the class's own constructor runs, in the order they are declared in the class.
Hint 2
They are destroyed after the body of the class's own destructor, in reverse order.
Hint 3
Pass the part names to the members in the member initializer list.
Solution
Show one correct solution (try it yourself first)
#include <iostream>
#include <string>
using namespace std;
class Part {
string name;
public:
Part(string n) : name(n) {
cout << "part " << name << " made" << endl;
}
~Part() {
cout << "part " << name << " removed" << endl;
}
};
class Room {
string name;
Part first;
Part second;
public:
Room(string r, string a, string b) : name(r), first(a), second(b) {
cout << "room " << name << " made" << endl;
}
~Room() {
cout << "room " << name << " closed" << endl;
}
};
int main() {
string r, a, b;
cin >> r >> a >> b;
Room room(r, a, b);
cout << "in use" << endl;
return 0;
}