Constructors & Destructors
Constructors and destructors are the machinery RAII rides on. Get them in your bones if you want to write correct C++.
Constructor Basics
A constructor sets up an object the moment it's born:
class Point { double x, y;public: Point() : x(0), y(0) {} // default constructor Point(double x, double y) : x(x), y(y) {} // parameterized constructor};
Point origin; // calls Point()Point p(3.0, 4.0); // calls Point(double, double)The : x(0), y(0) syntax is the member initializer list. Members get their values during construction, not afterwards via assignment.
Why Initializer Lists Matter
class Widget { const int id; std::string name;public: // GOOD: initializes directly Widget(int id, std::string name) : id(id), name(std::move(name)) {}
// BAD: would not compile - const members cannot be assigned // Widget(int id, std::string n) { this->id = id; name = n; }};Always use initializer lists. They skip the default-construct-then-assign dance, and they're outright required for const members, reference members, and any member without a default constructor.
Initialisation Order Follows the Declarations
The initialiser list has one trap. Members are initialised in the order they're declared in the class, whatever order you write them in the list.
class Range { int end; // declared first int begin; // declared secondpublic: Range(int b, int len) : begin(b), end(begin + len) {} int size() const { return end - begin; }};
Range r(10, 5);Predict: what does r.size() return?
Not 5, or at least nothing you can count on. Walk through the construction of r(10, 5):
endis declared first, so its initialiserend(begin + len)runs first.beginhasn't been initialised yet, so this reads an indeterminate value. That's undefined behaviour; in practice you get whatever was on the stack, say 32767 + 5.begin(b)runs second and setsbeginto 10.size()returns that garbage minus 10.
The list reads as if begin came first, which is exactly why it fools people. GCC and Clang both warn with -Wall (-Wreorder). The fix is to swap the two declarations so begin comes first, or to write end(b + len) so it doesn't depend on another member at all.
Make a habit of writing initialiser lists in declaration order. Then the code reads the way it runs.
explicit, Delegating Constructors and = default
A constructor that takes one argument doubles as an implicit conversion. With Buffer(std::size_t n), the line Buffer b = 16; compiles and quietly builds a 16-byte buffer, and so does passing 16 to any function that takes a Buffer. Mark single-argument constructors explicit and both become errors, while Buffer b(16); still works. The runnable Buffer further down does this.
One constructor can hand the work to another, so the setup logic lives in one place (C++11 onwards):
class Point { double x, y;public: Point(double x, double y) : x(x), y(y) {} Point() : Point(0, 0) {} // delegating constructor};And = default asks the compiler for its own version of a special member, which is handy once you've written another constructor and still want a default one: Widget() = default;. Its mirror image, = delete, removes a member entirely; you saw it stop FileHandle from being copied in the RAII lesson.
Destructor
The destructor runs when an object is destroyed:
class Logger { std::string name;public: Logger(const std::string &n) : name(n) { std::cout << name << " created" << std::endl; } ~Logger() { std::cout << name << " destroyed" << std::endl; }};
int main() { Logger a("first"); Logger b("second"); return 0;}// Output:// first created// second created// second destroyed// first destroyedThe Rule of Five
If your class owns a resource, you probably need all five special members:
class Buffer { char *data; size_t size;public: Buffer(size_t n) : data(new char[n]), size(n) {} // constructor ~Buffer() { delete[] data; } // destructor Buffer(const Buffer &other); // copy constructor Buffer &operator=(const Buffer &other); // copy assignment Buffer(Buffer &&other) noexcept; // move constructor Buffer &operator=(Buffer &&other) noexcept; // move assignment};Those are only declarations. Here's a full Buffer that announces each special member as it fires. Guess which line triggers which before you press Run.
Check your guesses: the run, line by line
Line in main | Output | What happened |
|---|---|---|
Buffer b1(16); | ctor(16) | ordinary constructor, 16 zeroed bytes |
Buffer b2 = b1; | copy ctor | new object from an existing one: fresh 16 bytes, contents copied |
Buffer b3 = std::move(b1); | move ctor | b3 takes b1's pointer; b1 is left with nullptr and size 0 |
b2 = b3; | copy assign | b2 already exists, so this is assignment, not construction |
b2 = alias; | copy assign | this == &other, so the body skips the delete-and-copy |
b3 = Buffer(8); | ctor(8), move assign, dtor (size 0) | the temporary is built, its buffer moves into b3 (whose old 16 bytes are freed), then the emptied temporary dies at the end of the statement |
end of main | dtor (size 8), dtor (size 16), dtor (size 0) | b3, b2, b1, in reverse order of construction |
Two things to take away. = in a declaration (Buffer b2 = b1;) is construction, not assignment. And the moved-from b1 still gets destroyed; it's just empty, which is why the move constructor has to leave it in a state where delete[] nullptr is safe. It is: deleting a null pointer does nothing.
Better yet, aim for the Rule of Zero: build your class out of RAII types like std::vector and std::unique_ptr, and let the compiler-generated defaults do the right thing for free.
Rule of Zero Example
class Person { std::string name; std::vector<std::string> hobbies;public: Person(std::string name, std::vector<std::string> hobbies) : name(std::move(name)), hobbies(std::move(hobbies)) {} // No destructor, copy constructor, or assignment operator needed! // The compiler generates correct versions automatically.};Compose RAII types and correct copying, moving and cleanup fall out for nothing. Person has no new, so it has no delete to forget either.
Challenges
Create a class that prints 'opened' on construction and 'closed' on destruction.