Skip to main content
Be Bitwise
C++C++ Basics & RAII

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:

cpp
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

cpp
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; }
};
Key Concept

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.

cpp
class Range {
int end; // declared first
int begin; // declared second
public:
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):

  1. end is declared first, so its initialiser end(begin + len) runs first. begin hasn'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.
  2. begin(b) runs second and sets begin to 10.
  3. 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):

cpp
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:

cpp
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 destroyed

The Rule of Five

If your class owns a resource, you probably need all five special members:

cpp
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.

Try itComment out the move constructor and see which member the compiler picks for b3 instead.
C++ (GCC 9.2.0)
Check your guesses: the run, line by line
Line in mainOutputWhat happened
Buffer b1(16);ctor(16)ordinary constructor, 16 zeroed bytes
Buffer b2 = b1;copy ctornew object from an existing one: fresh 16 bytes, contents copied
Buffer b3 = std::move(b1);move ctorb3 takes b1's pointer; b1 is left with nullptr and size 0
b2 = b3;copy assignb2 already exists, so this is assignment, not construction
b2 = alias;copy assignthis == &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 maindtor (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

cpp
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.

C++ (GCC 9.2.0)