C++ Programming: Objects, RAII and the STL ยท Classes and Objects
Constructors set objects up; destructors clean up automatically when they go out of scope. This is RAII.
#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;
}int main().name(n) sets up the members before the constructor body runs.open outer.Logger() has finished, so its variables are gone. outer is created on the stack with the value {name: "outer"}.name(n) sets up the members before the constructor body runs.open inner.Logger() has finished, so its variables are gone. inner is created on the stack with the value {name: "inner"}.working.close inner.~Logger() has finished, so its variables are gone. inner goes out of scope and disappears.done.0.~Logger() runs, because the object is going away.close outer.