1. Goals
Initialize members as an object is constructed, using a member initializer list.
Predict the construction and destruction order of class members.
Follow local objects when a block ends or a function returns early.
2. Prerequisites
You know classes, public/private, a simple constructor, std::string,
and the lifetime of local variables. The C++17 example prints messages
to reveal execution order. It does not open files or allocate resources manually.
3. Explanation
Members are constructed before the constructor body
In TracePart(const std::string& name) : name_(name), the part after :
is the member initializer list. name_(name) constructs the member
string name_ from the input string. By the time the constructor body
prints its message, name_ has been initialized. This is not a call to
a function named name_.
The parameter is a const reference, but name_ is a separate std::string
member. The string is copied into the member; no reference to the parameter
is retained. The object therefore keeps its name after the constructor returns.
If you omit : name_(name) and write name_ = name; in the body instead,
the member string is first initialized empty, then assigned a value.
The final name can be the same, but the steps differ. For a const int
or reference member, assignment in the constructor body cannot replace
initialization. Prefer to state the initial value in the initializer list.
Objects can contain other objects
StudySession contains two TracePart objects: screen_ and notes_.
This arrangement, where an object has component objects, is called
composition. Creating a session constructs its two members before
running the session's constructor body. You do not call their constructors
again inside that body.
TracePart only has a constructor that takes a name. StudySession
therefore supplies names through screen_("screen") and notes_("notes").
Omitting the initializer for a member makes the compiler try to construct
a TracePart with no arguments, but this class does not provide such a constructor.
The actual order is the order of member declarations in the class:
screen_ first, then notes_. Reversing entries in the initializer list
does not change that rule, so keep both orders consistent. In particular,
one member must not read the value of another member that is not initialized yet.
C++17 member initialization rules
define this order and place the constructor body last.
Destructors and destruction order
~TracePart() is a destructor: the class name is prefixed with ~,
with no return type or parameters. For an automatic local object such as
exercise, it is called when leaving the object's enclosing block.
The destructor messages only make the example observable; you do not need
to write a destructor just to destroy ordinary std::string members correctly.
When session is destroyed, the body of ~StudySession() runs first.
After that body finishes, its members are automatically destroyed in reverse
construction order: notes_, then screen_. While ~TracePart() prints
its message, its name_ remains usable; that member string is destroyed
after the destructor body.
C++17 destructor rules
describe member destruction after the destructor body and this reverse order.
An early return still ends local object lifetimes
exercise is inside a nested block, so it has already been destroyed before
Return early is printed. The following return leaves study, destroying
session and its members before execution continues in main.
Changing the call to study(false) reaches the end of the function body
and still destroys session in the same order.
These observations concern ordinary block exits and returns for the
automatic local objects in this example. Do not conclude that destructors
must run when a process is forcibly terminated. Do not explicitly call
session.~StudySession() to "clean up early", either: that ends the object's
lifetime while block exit will still try to destroy it again. Use a nested
block when you want an object to have a shorter lifetime.
After Foundation, destructors and RAII in the C++11 track revisits how object destruction supports resource management.
4. Runnable example
Save as main.cpp and compile as C++17. No input is required.
#include <iostream>
#include <string>
class TracePart {
public:
explicit TracePart(const std::string& name) : name_(name) {
std::cout << "Construct " << name_ << '\n';
}
~TracePart() {
std::cout << "Destroy " << name_ << '\n';
}
private:
std::string name_;
};
class StudySession {
public:
StudySession() : screen_("screen"), notes_("notes") {
std::cout << "Session ready\n";
}
~StudySession() {
std::cout << "Session closing\n";
}
private:
TracePart screen_;
TracePart notes_;
};
void study(bool stopEarly) {
StudySession session;
{
TracePart exercise{"exercise"};
std::cout << "Exercise running\n";
}
if (stopEarly) {
std::cout << "Return early\n";
return;
}
std::cout << "Keep studying\n";
}
int main() {
std::cout << "Before study\n";
study(true);
std::cout << "Returned to main\n";
return 0;
}Exact output:
Before study
Construct screen
Construct notes
Session ready
Construct exercise
Exercise running
Destroy exercise
Return early
Session closing
Destroy notes
Destroy screen
Returned to main5. Common mistakes
Assuming members are initialized in the order written after the
:.Assigning to a member in the constructor body and calling it direct initialization.
Expecting a no-argument constructor after declaring only a constructor that takes a name.
Thinking
returnskips destruction of fully constructed automatic local objects.Calling a local object's destructor explicitly instead of letting its block manage it.
Writing an empty destructor for every class: with members such as strings that manage themselves, the destructor provided by C++ is often sufficient.
6. Practice
Before running, write the complete message order. Mark the messages for
exercise, the destructor body ofsession, and its two members.Replace
study(true)withstudy(false). OnlyReturn earlychanges toKeep studying; the remaining construction and destruction order stays the same.Add
TracePart timer_;afternotes_, withtimer_("timer")at the end of the initializer list.Construct timermust appear beforeSession ready;Destroy timermust appear afterSession closingand beforeDestroy notes.Remove only the user-written
StudySessiondestructor.Session closingdisappears, butDestroy notesandDestroy screenstill appear in that order. Explain why the members are still destroyed.
7. Self-check
Are
screen_andnotes_constructed before or afterSession ready? Answer: before. Members are initialized in declaration order before the body of theStudySessionconstructor starts.Why does
Session closingappear beforeDestroy notes? Answer: the containing object's destructor body runs first; C++ then destroys its members in reverse construction order.Does an early return leave
sessionalive afterstudyreturns? Answer: no.sessionis a fully constructed automatic local object; returning destroys it and its members before execution continues inmain.
Sample code
Source file
cpp98_foundation/14_constructors_destructors/main.cpp
#include <iostream>
#include <string>
class TracePart {
public:
explicit TracePart(const std::string& name) : name_(name) {
std::cout << "Construct " << name_ << '\n';
}
~TracePart() {
std::cout << "Destroy " << name_ << '\n';
}
private:
std::string name_;
};
class StudySession {
public:
StudySession() : screen_("screen"), notes_("notes") {
std::cout << "Session ready\n";
}
~StudySession() {
std::cout << "Session closing\n";
}
private:
TracePart screen_;
TracePart notes_;
};
void study(bool stopEarly) {
StudySession session;
{
TracePart exercise{"exercise"};
std::cout << "Exercise running\n";
}
if (stopEarly) {
std::cout << "Return early\n";
return;
}
std::cout << "Keep studying\n";
}
int main() {
std::cout << "Before study\n";
study(true);
std::cout << "Returned to main\n";
return 0;
}