Skip to content
UPEEC

Constructors and Destructors

Constructors set an object up; destructors clean it up automatically when it goes out of scope.

Intermediate
Comments 0
class File {
public:
    File(const char *path) { f_ = std::fopen(path, "r"); }   // acquire
    ~File() { if (f_) std::fclose(f_); }                      // release
private:
    std::FILE *f_;
};

void read() {
    File f("data.txt");
}   // destructor runs here, even if an exception is thrown

Use the member initialiser list (: pin_(pin)) to initialise members. Destructors are the basis of RAII.

Spotted a mistake or want to add detail? Suggest an improvement — Content Contributors' edits are reviewed by editors before they go live.

Discussion (0)

Sign in or join free to ask questions and discuss this topic.