Constructors & Destructors
Prerequisites: Introduction to classes & objects
A constructor initializes an object when it's created; a
destructor runs automatically when it's destroyed — when a
stack object goes out of scope, or a heap object is explicitly
deleted.
class Dog {
public:
std::string name;
Dog(std::string n) : name(n) { // member initializer list
std::cout << name << " created" << std::endl;
}
~Dog() {
std::cout << name << " destroyed" << std::endl;
}
};
int main() {
Dog rex("Rex");
std::cout << "Using rex..." << std::endl;
return 0;
// rex's destructor runs automatically here
}
Rex created
Using rex...
Rex destroyed
This automatic, guaranteed-to-run destructor is the foundation of RAII (Resource Acquisition Is Initialization) — a class that acquires a resource in its constructor and releases it in its destructor can never leak that resource, covered fully in Level 2.
Common mistakes
- Preferring
name = n;in the constructor body over the member initializer list (: name(n)) — the initializer list is more efficient and, for some member types, required.