8.2 Constructors, Destructors, and Lifetime
C++ objects have precise lifetimes. A constructor runs when an object is created. A destructor runs when the object is destroyed. This is one of the most important differences between C++ and Java or Python: C++ lets ordinary objects manage resources directly and deterministically.
Constructors and initialization lists
A constructor has the same name as the class and no return type. It should put the object into a valid state immediately.
class BankAccount {
private:
std::string owner_;
double balance_;
public:
BankAccount(std::string owner, double balance)
: owner_(owner), balance_(balance) {}
};The part after : is the member initializer list. It initializes members before the constructor body runs. Prefer initialization lists for data members, especially for const members, references, and class-type members such as std::string.
class Student {
private:
const int id_;
std::string name_;
public:
Student(int id, std::string name)
: id_(id), name_(name) {}
};If you try to assign to id_ inside the constructor body, it is too late because const members must be initialized, not assigned later.
Overloaded and delegating constructors
C++ classes can provide several constructors. This is useful when there is a full form and a convenient default form.
class Timer {
private:
int seconds_;
public:
Timer() : Timer(0) {}
Timer(int minutes, int seconds)
: seconds_(minutes * 60 + seconds) {}
explicit Timer(int seconds)
: seconds_(seconds) {}
};Timer() : Timer(0) {} is a delegating constructor: it reuses another constructor in the same class. explicit prevents surprising implicit conversions such as passing an int where a Timer was expected.
Destructors and RAII
A destructor has the form ~ClassName(). It runs automatically when an object leaves scope or when delete destroys a heap object.
class Buffer {
private:
int *data_;
int size_;
public:
explicit Buffer(int size)
: data_(new int[size]), size_(size) {}
~Buffer() {
delete[] data_;
}
};This pattern is called RAII: Resource Acquisition Is Initialization. The object acquires a resource in its constructor and releases it in its destructor. RAII is the heart of safe C++ design.
For beginner code, prefer standard library classes such as std::string, std::vector, and smart pointers. They already implement RAII. But understanding destructors explains why those types are safe.