Skip to content

Constructors, destructors, and object lifetime

Difficulty: Beginner

Key concepts

  • constructor
  • destructor
  • lifetime
  • scope
  • member initializer list
  • explicit
  • temporary
  • destruction order
  • How a constructor makes an object valid from its first moment.
  • Why member initializer lists and explicit matter for design.
  • Exactly when C++ destroys an object, and in what order.
  • How scope decides an object’s lifetime, and why that is a design tool.

In garbage-collected languages such as Java or Python, an object lives until the runtime notices nobody uses it, and you rarely know exactly when that is. In C++, for most objects, you can point to the line where an object is created and the line where it is destroyed. That precision is what lets a C++ object release a file, a lock, or a network connection at a known moment, and it is also what makes a reference to a destroyed object a real danger.

An object’s lifetime starts when its constructor finishes and ends when its destructor starts. Two special member functions bracket it:

  • a constructor, which runs when the object is created and makes it valid;
  • a destructor, which runs when the object is destroyed and releases whatever it holds.

The previous lesson’s Book checked its rules in its constructor, so an invalid Book could never exist. Here is the same idea on a smaller type. A loan lasts between 1 and 90 days:

VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).

loan_period.hpp
// How long one loan lasts, in days. Build it from an int; read it back
// with days(). Throws std::out_of_range for anything outside 1 to 90.
// Invariant: 1 <= days() <= 90. There is no way to change the value, so the
// constructor is the only place the rule needs checking.
class LoanPeriod {
public:
// `explicit`: an int is not silently turned into a LoanPeriod.
// `: days_(checked(days))` is the member initializer list: it gives
// days_ its value before the (empty) body `{}` runs. The value it uses
// is whatever checked(days) returns, and checked throws for a bad
// value, so days_ is never set to a bad number, not even for a moment.
explicit LoanPeriod(int days) : days_(checked(days)) {}
[[nodiscard]] int days() const noexcept { return days_; }
private:
// A private helper: returns `days` unchanged if it is in range, and
// throws otherwise. `static` means it belongs to the class, not to one
// object, so it cannot read days_ by mistake (days_ has no value yet
// when the initializer list calls it); it needs only its argument.
// `days < 1 || days > 90` is true when the value is below the range OR
// above it; 1 and 90 themselves are accepted.
static int checked(int days) {
if (days < 1 || days > 90) throw std::out_of_range("loan period must be 1 to 90 days");
return days;
}
int days_; // no "= ..." default: the constructor always sets it
};

Recall from the previous lesson that an invariant is a rule that must always hold for an object. Two markers from the conventions page appear again: [[nodiscard]] makes the compiler warn if a caller ignores the result, and noexcept promises the function will not throw an exception. Several design decisions are packed into these few lines.

  • The constructor is the only way in. There is no default constructor and no setter, so every LoanPeriod that exists went through the check. Code that receives a LoanPeriod never needs to check it again.
  • The check happens in the member initializer list. The part after the colon, : days_(checked(days)), initializes days_ directly, before the constructor body runs. The small helper checked throws if the value is out of range, so days_ is never set to a bad value, even briefly.
  • Throwing means the object never existed. If a constructor throws, the object’s lifetime never starts, and its destructor does not run. Any members that were already constructed are destroyed, so nothing leaks, and the caller cannot end up holding a half-built object.
  • explicit prevents silent conversions. Without it, C++ would let an int turn into a LoanPeriod wherever one is expected, so renew(loan, 14) would compile even if the author meant 14 weeks. With explicit, the caller must write LoanPeriod(14), which names the unit’s type at the call site.

IllustrativeA fragment for explanation; not compiled on its own.

// Extends `loan` by `extra`. The parameter type is LoanPeriod, not int, so
// every value that reaches renew has already passed the 1-to-90 check.
void renew(Loan& loan, LoanPeriod extra);
renew(loan, 14); // error: no implicit conversion from int
renew(loan, LoanPeriod(14)); // fine: the conversion is visible

The tests check both ends of the range, values outside it, and, with static_assert, that the compiler really refuses an implicit conversion:

VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).

test_loan_period.cpp
// LLD_TEST, LLD_CHECK_EQ, and LLD_CHECK_THROWS come from the site's test
// header, lld_test.hpp (the previous lesson's tests explain each one).
// The two edges of the range, 1 and 90, are the values most likely to be
// wrong (a `<` where `<=` was meant), so they are tested directly. Each
// line builds a temporary LoanPeriod and reads its days() back.
LLD_TEST(accepts_the_boundaries) {
LLD_CHECK_EQ(LoanPeriod(1).days(), 1);
LLD_CHECK_EQ(LoanPeriod(90).days(), 90);
}
// One step outside each edge (0 and 91), and a negative number. Each
// passes only if constructing the LoanPeriod throws std::out_of_range.
LLD_TEST(rejects_values_outside_the_range) {
LLD_CHECK_THROWS(LoanPeriod(0), std::out_of_range);
LLD_CHECK_THROWS(LoanPeriod(91), std::out_of_range);
LLD_CHECK_THROWS(LoanPeriod(-14), std::out_of_range);
}
// `explicit` is checked by the compiler: an int does not convert implicitly.
// static_assert(condition) fails the build if the condition is false.
// std::is_convertible_v<int, LoanPeriod> asks "can an int silently become
// a LoanPeriod?" and must be false (hence the `!`).
// std::is_constructible_v<LoanPeriod, int> asks "can you build one from an
// int if you write LoanPeriod(14)?" and must be true. Together they prove
// the conversion exists but only when written out.
static_assert(!std::is_convertible_v<int, LoanPeriod>);
static_assert(std::is_constructible_v<LoanPeriod, int>);

A static_assert is checked while the code compiles: if the condition is false, the build fails. So the explicit guarantee is tested even though no code runs.

You could write the constructor as LoanPeriod(int days) { days_ = checked(days); }. For an int the effect is the same. In general it is not:

  • Without an initializer list entry, each member is first default-initialized (given whatever starting value its type gives by default: an empty string, or, for an int, no defined value at all) and then assigned in the body: two steps instead of one. For a std::string that means building an empty string and then replacing it.
  • Some members cannot be assigned at all: const members, reference members, and members of types with no default constructor. They must be initialized in the list.

Use the initializer list for every member, and use the body only for work that needs the members to exist already. For a member whose starting value never depends on constructor arguments, a default member initializer in the class, such as int copies_on_loan_ = 0; in Book, is simplest.

To see construction and destruction, here is a class that prints a line in each:

VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).

tracer.hpp
// A class that does nothing but announce itself: one line of output when
// an object is created, one when it is destroyed. Give each object a name,
// and the program's output becomes a record of exactly when each lifetime
// starts and ends.
class Tracer {
public:
// The constructor. `name` is the constructor's own string (by value), so
// std::move hands its characters over to name_ instead of copying them
// again. The body runs after name_ exists, so it can print it.
explicit Tracer(std::string name) : name_(std::move(name)) {
std::cout << " construct " << name_ << '\n';
}
// The destructor: same name as the class with a `~` in front, no
// parameters, no return type. Nobody calls it by hand; C++ calls it
// automatically when the object's lifetime ends. name_ is destroyed
// just after this body finishes, so the body can still print it.
~Tracer() { std::cout << " destroy " << name_ << '\n'; }
private:
std::string name_;
};

The destructor is the function named ~Tracer. It takes no arguments and cannot be called with different options: C++ calls it automatically when the object’s lifetime ends. A class with members that hold resources, such as std::string, usually needs no destructor at all, because each member’s own destructor runs automatically. Tracer has one only to print.

A function with a local object:

VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).

main.cpp
// `loan` is a local variable: it lives inside this function's braces only.
// It is created on its line, and destroyed automatically when the function
// returns, after the last line has run.
void lend_book() {
std::cout << "lend_book starts\n";
Tracer loan("loan");
std::cout << "lend_book returns\n";
} // `loan` is destroyed here, at the function's closing brace

And a program that creates objects in different scopes:

VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).

main.cpp
std::cout << "main starts\n";
Tracer catalog("catalog"); // lives until the end of main
{
// A bare pair of braces starts a new scope. Anything declared inside
// is destroyed at the closing brace, even though main goes on.
std::cout << "inner scope starts\n";
Tracer member("member");
std::cout << "inner scope ends\n";
} // `member` is destroyed here
lend_book(); // `loan` is created and destroyed inside the call
std::cout << "temporary:\n";
// No variable name, so no object to keep: the Tracer is built, then
// destroyed when the statement finishes, at the semicolon.
Tracer("receipt"); // a temporary, destroyed at the end of this statement
std::cout << "session:\n";
// Session (defined in tracer.hpp) is a class with two Tracer members,
// log_ named "session.log" and cache_ named "session.cache", declared
// in that order. Its constructor and destructor bodies each print a line.
Session session;
std::cout << "main ends\n";
// At main's closing brace, the objects still alive are destroyed in the
// reverse order of their creation: `session` first, then `catalog`.
Expected output
main starts
construct catalog
inner scope starts
construct member
inner scope ends
destroy member
lend_book starts
construct loan
lend_book returns
destroy loan
temporary:
construct receipt
destroy receipt
session:
construct session.log
construct session.cache
session body runs
main ends
session destructor body runs
destroy session.cache
destroy session.log
destroy catalog

Read the output against the code. Each rule below is visible in it.

  1. A local object is destroyed when its scope ends. A scope is a region of code between braces. member is destroyed at the closing brace of the inner block, before lend_book is called. loan is destroyed when lend_book returns, after its last line runs.
  2. A temporary is destroyed at the end of its full statement. Tracer("receipt"); creates an object with no name. It is destroyed at the semicolon, so “destroy receipt” comes immediately after “construct receipt”. (Writing Tracer receipt("receipt"); instead would create a named object that lives to the end of the scope.)
  3. Members are constructed before the constructor body runs, in declaration order. session.log and session.cache are constructed, then “session body runs” is printed.
  4. Destruction is the reverse of construction. At the end of main, the objects still alive are destroyed in reverse order: session first (its destructor body, then its members in reverse order: cache before log), then catalog, which was created first.

Rule 4 is not arbitrary. An object created later may depend on one created earlier (a session may write to a log created before it), so destroying the later one first means nothing is destroyed while something still uses it.

When each object in the program is constructed and destroyed
Text description of the diagram

A timeline of the program, top to bottom. main constructs catalog first. Inside the inner scope it constructs member, which is destroyed at that scope’s closing brace. Then lend_book runs: it constructs loan, which is destroyed when lend_book returns. (The receipt temporary, created and destroyed in one statement, is left out to keep the picture small.) Next main constructs session: its members log and cache first, then its constructor body. When main ends, session is destroyed first (its destructor body, then cache, then log), and catalog, the first object created, is destroyed last.

Diagram source (Mermaid)
sequenceDiagram
participant main
participant catalog
participant member
participant loan
participant session
main->>catalog: construct
Note over main,member: inner scope
main->>member: construct
main->>member: destroy at closing brace
Note over main,loan: lend_book() runs
main->>loan: lend_book constructs
main->>loan: destroyed when lend_book returns
main->>session: construct log, cache, then body
Note over main: main ends
main->>session: destroy body, then cache, then log
main->>catalog: destroy last

Every object in the example has automatic storage duration: it lives in a scope and is destroyed when the scope ends. This is the default, and the best choice whenever it fits, because the compiler guarantees destruction on every path out of the scope, including when an exception is thrown (and caught somewhere up the call chain).

Two other kinds appear in later lessons:

  • Dynamic lifetime: an object created with new lives until something destroys it explicitly. Modern C++ hands that job to an owning object such as std::unique_ptr, so the destruction is again tied to a scope. The ownership, RAII, and smart pointer lessons cover this.
  • Static lifetime: global variables and static local variables live until the program ends. They are hard to test, and global variables in different files are created in an order that is hard to control, so this site avoids them in designs.

Write a constructor when the type has an invariant: a value range, a non-empty name, a relationship between members. Make the constructor reject bad input, so the rest of the code can trust every object.

Do not write one when the type is a plain struct with no rule. BookDetails in the previous lesson has no constructor; it is built with braces, {"978-0201633610", "Design Patterns"}, and that is clearer.

Mark single-argument constructors explicit unless the conversion is truly natural and harmless, for example a std::string from a string literal. Most domain types (LoanPeriod, MemberId, Isbn) should be explicit.

Throwing constructors versus a factory function. A constructor can report a problem only by throwing. If bad input is an expected, everyday event (a user typing a loan period in a form), throwing may be the wrong tool. An alternative is a static function such as static std::optional<LoanPeriod> parse(int days) that returns “nothing” for bad input, with a private constructor. That costs a little more code and makes every caller handle the empty case. The error handling lessons compare these options.

Two-phase initialization is not a good alternative. Some older code has a constructor that does nothing and an init() function that must be called before use. Every member function must then check whether init() was called, and every caller can forget. Prefer making the constructor do the work.

Destructors should not fail. Destructors are noexcept by default: if an exception escapes one, the program terminates. A destructor should release resources and nothing more. If releasing can fail in a way the caller must know about (such as flushing a file to disk), offer an explicit function such as close() that reports errors, and let the destructor clean up quietly if it was not called.

  • Assigning members in the constructor body. It works for simple types but wastes work, and fails for const and reference members. Use the initializer list.
  • Initializer list in a different order from the declarations. The declaration order wins, which can read an uninitialized member.
  • Forgetting explicit. Single-argument constructors become silent conversions.
  • An init() function. It leaves a window in which the object exists but is not valid.
  • Doing risky work in a destructor. Anything that can throw or block for a long time belongs in an explicit function.
  • Keeping a reference to an object after its scope ends. The reference dangles.

New requirement: “Students may borrow for at most 28 days; everyone else for up to 90.”

It is tempting to give LoanPeriod a second constructor parameter for the member type. That would make LoanPeriod depend on membership rules it has no other reason to know. A better split: LoanPeriod keeps its absolute rule (1 to 90 days), which is true for everyone, and a separate loan policy checks the member-specific limit, which can change without touching LoanPeriod. A constructor should enforce the rules that are always true for the type itself; rules that depend on context belong to the code that has the context.

Exercise: Predict construction and destruction order

Write down, in order, every line this program prints. Tracer is the class from this page. Then check your answer.

VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).

exercise.cpp
// A struct with two Tracer members. `Tracer lamp{"lamp"};` is a default
// member initializer: every Desk builds its lamp from "lamp", and its
// chair from "chair", without Desk having to write a constructor.
struct Desk {
Tracer lamp{"lamp"};
Tracer chair{"chair"};
};
int main() {
Tracer a("a");
Desk desk;
// The loop body runs twice, with i = 1 and then i = 2.
// std::to_string(i) turns the number into text, so the names are
// "step 1" and "step 2".
for (int i = 1; i <= 2; ++i) {
Tracer step("step " + std::to_string(i));
}
Tracer("note");
Tracer b("b");
}
Show the explained answer

This program is part of the examples, and this output is checked against its real output on every validation run:

Expected output
construct a
construct lamp
construct chair
construct step 1
destroy step 1
construct step 2
destroy step 2
construct note
destroy note
construct b
destroy b
destroy chair
destroy lamp
destroy a

Why:

  • a is constructed first. Then desk: its members in declaration order, lamp then chair. (Desk has no constructor of its own; the braces after each member are default member initializers.)
  • Each loop iteration is its own scope, so step 1 is destroyed before step 2 is constructed.
  • Tracer("note"); is a temporary, destroyed at the end of its statement.
  • At the end of main, the remaining objects are destroyed in reverse order of construction: b, then desk (whose members go in reverse, chair before lamp), then a.

The most common wrong answers are destroying lamp before chair, and leaving note alive until the end of main.

  • A constructor makes an object valid; if it throws, the object never existed.
  • Initialize members in the initializer list, in declaration order; use default member initializers for fixed starting values.
  • Mark single-argument constructors explicit to prevent silent conversions.
  • Local objects are destroyed when their scope ends, temporaries at the end of their statement, and objects in reverse order of construction.
  • Destructors release resources, run automatically, and must not throw.