C++: Constructor and destructor order

Complete the class Guard: its constructor takes a name and prints open NAME, and its destructor prints close NAME. main (already written) creates guards in a particular order; the output shows when each one is built and destroyed.

What to build

A Guard class whose constructor and destructor report when they run.

Requirements

  • Store the name in a member.
  • Print open NAME in the constructor.
  • Print close NAME in the destructor.

Input

Three names, one per line.

Output

One line for each construction and destruction, in the order they happen.

Constraints

Three names, each one word.

Example

Input:

door
window
gate

Output:

open door
open window
close window
open gate
end of main
close gate
close door

Why it works

Local objects are destroyed at the end of their block in reverse order of creation, so the output shows exactly when each guard is built and destroyed.

Examples

Example 1 · Input
door
window
gate
Expected output
open door
open window
close window
open gate
end of main
close gate
close door
Example 2 · Input
a
b
c
Expected output
open a
open b
close b
open c
end of main
close c
close a

Hints

Hint 1

The constructor prints open NAME and the destructor prints close NAME.

Hint 2

Store the name in a member, so the destructor still knows it.

Hint 3

A local object dies at the end of its block, newest first.

Solution

Show one correct solution (try it yourself first)
#include <iostream>
#include <string>
using namespace std;

class Guard {
    string name;
public:
    Guard(string name) : name(name) {
        cout << "open " << name << endl;
    }
    ~Guard() {
        cout << "close " << name << endl;
    }
};

int main() {
    string a, b, c;
    cin >> a >> b >> c;
    Guard first(a);
    {
        Guard second(b);
    }
    Guard third(c);
    cout << "end of main" << endl;
    return 0;
}

Lesson: Constructors and destructors →