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.
0 of 10 checks passed
Your progress is saved on this device.