Skip to content

Chapter 13 of 31

Constructors and Destructors

Control object lifetime with initialization lists, special members, and RAII cleanup.

40 minutes 10 quick checksBy Subha Prasad
Lesson 13 of 31Course navigation

Lesson content

Read, practise, then check your understanding

A constructor establishes a valid object. A destructor releases its resources. Members are initialized before the constructor body in declaration order—not initializer-list order—so declare dependent members carefully.

#include <string>
#include <utility>

class Session {
    std::string user_;
    bool active_{false};
public:
    explicit Session(std::string user)
        : user_{std::move(user)}, active_{true} {}

    ~Session() { active_ = false; }

    Session(const Session&) = delete;
    Session& operator=(const Session&) = delete;
};

explicit prevents surprising implicit conversion from a single argument. Delegating constructors reuse another constructor. = default requests the compiler-generated operation; = delete rejects an operation with a clear diagnostic.

The special members

C++ can generate a default constructor, destructor, copy constructor, copy assignment, move constructor, and move assignment. If a class directly manages a resource, it may need the Rule of Five. Prefer the Rule of Zero: store resources in std::string, containers, and smart pointers so their correct operations compose automatically.

Destruction runs in reverse construction order. Derived parts are destroyed before base parts; members are destroyed in reverse declaration order. Constructors should not publish a partially formed object, and destructors should not throw. A failed constructor destroys already-constructed subobjects, making RAII essential for exception safety.

Knowledge check

Answer every question correctly to complete this chapter.

When does a constructor run?
What initializes members before the constructor body?
When does a destructor run for an automatic object?
What syntax requests a compiler-generated special member?
What rule is often best for resource-owning members?
In what order are members initialized?
What does explicit prevent for a single-argument constructor?
What is a delegating constructor?
In what order are base and derived destructors run?
What syntax forbids copying?

0 of 10 checks passed

Your progress is saved on this device.