C++ Programming: Objects, RAII and the STL ยท Classes and Objects

Constructors, Destructors and RAII

Constructors set objects up; destructors clean up automatically when they go out of scope. This is RAII.

constructors_destructors.cpp

#include <iostream>
#include <string>
using namespace std;

class Logger {
    string name;
public:
    Logger(string n) : name(n) {          // constructor with an initialiser list
        cout << "open " << name << endl;
    }
    ~Logger() {                           // destructor: runs automatically at the end of the scope
        cout << "close " << name << endl;
    }
};

int main() {
    Logger outer("outer");
    {
        Logger inner("inner");
        cout << "working" << endl;
    }                                     // inner is destroyed here
    cout << "done" << endl;
    return 0;
}

Step by step

  1. C++ enters int main().
  2. Creating outer runs the constructor.
  3. The initialiser list name(n) sets up the members before the constructor body runs.
  4. It prints open outer.
  5. Logger() has finished, so its variables are gone. outer is created on the stack with the value {name: "outer"}.
  6. inner lives only inside these braces.
  7. The initialiser list name(n) sets up the members before the constructor body runs.
  8. It prints open inner.
  9. Logger() has finished, so its variables are gone. inner is created on the stack with the value {name: "inner"}.
  10. It prints working.
  11. The block ends: inner's destructor runs now.
  12. It prints close inner.
  13. ~Logger() has finished, so its variables are gone. inner goes out of scope and disappears.
  14. It prints done.
  15. The method returns 0.
  16. The destructor ~Logger() runs, because the object is going away.
  17. It prints close outer.
  18. open outer, open inner, working, close inner, done, close outer.