Module 4 · Your own types
4.2Constructors, destructors and the rule of zero
Make every object start valid with a constructor, set members in the initializer list, see the order C++ builds and destroys members in, and learn why most classes need no destructor at all.
On this page
- Key terms
- In 30 seconds
- A constructor sets up every new object
- The member initializer list
- Default member initializers
- Several constructors, one setup
- explicit: no surprise conversions
- Destructors, and the order of everything
- Members are created in declaration order
- The rule of zero
- Which one should I use?
- Under the hood
- Common pitfalls
- No default constructor after you write one
- Empty parentheses don’t call the default constructor
- Try it yourself
Key terms
- constructor
- A member function named after the class, with no return type, that runs when an object is created. It sets up the members and can check its arguments.
- member initializer list
- The part of a constructor between
:and the body, like: start_(start), end_(end). It creates each member with the value given. - default member initializer
- A starting value written where the member is declared:
int min_quality = 20;. It's used when a constructor doesn't set that member. - default constructor
- A constructor that can be called with no arguments. It runs for
Interval empty;andInterval empty{};. - delegating constructor
- A constructor whose initializer list calls another constructor of the same class, so the setup code lives in one place.
explicit- Written before a constructor, it stops C++ from using that constructor to convert a value to your type without being asked. You can still call it by name.
- destructor (
~T()) - A member function named
~plus the class name that runs when an object is destroyed. After its body, the members are destroyed in reverse order. - special member functions
- The six functions the compiler can write for a class by itself: the default constructor, the destructor, the copy constructor and copy assignment, and the move constructor and move assignment.
- rule of zero
- Build a class from members that clean up after themselves, and write no destructor, copy or move functions for it.
In Structs and classes, a Read could be created with members missing, and Sequence had to rely on a std::string starting empty. A constructor closes that gap: it runs every time an object is created, so no object of the type can start out invalid. Dynamic memory and RAII used one in Buffer, with a destructor to match. This lesson covers both in full, and the rule that means you rarely write a destructor at all.
In 30 seconds
- A constructor is a member function named after the class, with no return type. It runs when the object is created and can check or fix its arguments.
- Set members in the member initializer list,
: start_(start), end_(end), and give members default values where they’re declared. - Members are created in the order they’re declared, before the constructor body runs. They’re destroyed in reverse, after the destructor body.
- Rule of zero: build classes from members that clean up after themselves, like
std::vectorandstd::unique_ptr, and write no destructor.
A constructor sets up every new object
A genomic interval runs from a start position to an end position, and the start must not be after the end. A constructor can make sure of that. It’s named after the class and has no return type:
#include <print>
#include <utility>
class Interval {
public:
Interval(int start, int end) : start_(start), end_(end) {
if (start_ > end_) {
std::swap(start_, end_);
}
}
int length() const { return end_ - start_; }
private:
int start_;
int end_;
};
int main() {
Interval gene(100, 250);
Interval reversed{80, 20};
std::println("{} {}", gene.length(), reversed.length());
}Output
150 60
Interval gene(100, 250) and Interval reversed{80, 20} both call the constructor with two arguments; the braces also refuse narrowing conversions, as in Variables. If the positions come in the wrong order, the constructor swaps them with std::swap from <utility>. No Interval can exist with its start after its end: that’s the invariant from the last lesson, now kept from the first moment.
The member initializer list
The part between : and { is the member initializer list. start_(start) creates the member start_ with the value start. It runs before the constructor body, so by the time the body starts, every member already exists.
You could assign in the body instead, start_ = start;, and for an int the result is the same. But then the member is first created and only set afterwards: a std::string member would be built empty and then replaced. For a member that can’t be assigned, such as a const member, that doesn’t compile:
class Sample {
public:
Sample(int lane) { lane_ = lane; }
private:
const int lane_;
};
int main() {
Sample sample(3);
}The compiler rejects this
main.cpp: In constructor ‘Sample::Sample(int)’:
main.cpp:3:5: error: uninitialized const member in ‘const int’ [-fpermissive]
3 | Sample(int lane) { lane_ = lane; }
| ^~~~~~
main.cpp:6:15: note: ‘const int Sample::lane_’ should be initialized
6 | const int lane_;
| ^~~~~
compilation terminated due to -fmax-errors=1.A const member must get its value when it’s created, so it must be in the initializer list: Sample(int lane) : lane_(lane) {}. Make the initializer list your habit for every member, and keep the body for checks and work that needs all the members ready.
Default member initializers
A member can have a starting value right where it’s declared. That value is used whenever a constructor doesn’t set the member. A struct with them is still an aggregate, so designated initializers can leave those members out, which is the fix for the “missing initializer” error from the last lesson:
#include <cstddef>
#include <print>
struct Filter {
int min_quality = 20;
std::size_t min_length = 50;
bool drop_n = true;
};
int main() {
Filter standard;
Filter strict{.min_quality = 30};
std::println("{} {} {}", standard.min_quality, standard.min_length,
standard.drop_n);
std::println("{} {} {}", strict.min_quality, strict.min_length,
strict.drop_n);
}Output
20 50 true 30 50 true
In a class with constructors, the same rule holds: a member named in the initializer list gets that value, and every other member gets its default. So a class can write int passed_ = 0; once, where the member is declared, instead of passed_(0) in every constructor.
Common pitfallEvery member needs a starting value
A constructor that leaves an int or a pointer member out of its initializer list, with no default, leaves it uninitialized. Reading it is undefined behavior, and the sanitizers this course uses don’t catch it. A default like int passed_ = 0; makes the mistake impossible.
Several constructors, one setup
A class can have several constructors, as long as their parameters differ, like overloaded functions (Functions). To avoid repeating the setup code, a delegating constructor names another constructor of the same class in its initializer list:
#include <print>
#include <utility>
class Interval {
public:
Interval(int start, int end) : start_(start), end_(end) {
if (start_ > end_) {
std::swap(start_, end_);
}
}
Interval(int position) : Interval(position, position + 1) {}
Interval() : Interval(0, 0) {}
int length() const { return end_ - start_; }
private:
int start_;
int end_;
};
int main() {
Interval gene(100, 250);
Interval snp(42);
Interval empty;
std::println("{} {} {}", gene.length(), snp.length(), empty.length());
}Output
150 1 0
Interval(42) covers the single position 42, and the swap check is still written once. A constructor that can be called with no arguments is the default constructor; it’s what runs for Interval empty;.
explicit: no surprise conversions
A constructor that can be called with one argument does a second job: C++ uses it to convert that argument’s type into your type, without being asked. With an Interval(int position) constructor like the one above, this compiles and runs:
#include <print>
class Interval {
public:
Interval(int position) : start_(position), end_(position + 1) {}
int length() const { return end_ - start_; }
private:
int start_;
int end_;
};
void print_length(Interval interval) {
std::println("length {}", interval.length());
}
int main() {
print_length(500); // a length of 500?
}Output
length 1
The caller probably meant a length of 500. C++ quietly built Interval(500), a one-base interval at position 500. Mark the constructor explicit and that implicit conversion becomes a compile error:
#include <print>
class Interval {
public:
explicit Interval(int position) : start_(position), end_(position + 1) {}
int length() const { return end_ - start_; }
private:
int start_;
int end_;
};
void print_length(Interval interval) {
std::println("length {}", interval.length());
}
int main() {
print_length(500);
}The compiler rejects this
main.cpp: In function ‘int main()’:
main.cpp:18:18: error: could not convert ‘500’ from ‘int’ to ‘Interval’
18 | print_length(500);
| ^~~
| |
| intWhen you do mean an interval, say so: print_length(Interval(500)).
Key ideaMake one-argument constructors explicit
Write explicit on every constructor that can be called with one argument, unless the conversion is the point (like building a std::string from "text"). The compiler then tells you about each conversion instead of making it silently.
Destructors, and the order of everything
The destructor is the constructor’s partner: ~ plus the class name, no parameters, no return type. It runs when the object is destroyed: at the end of its scope, or when its owner deletes it. You’ve seen it free memory in Buffer. This program prints from both, so you can see the whole order for a class whose members are objects too:
#include <print>
#include <string>
class Stage {
public:
explicit Stage(std::string name) : name_(name) {
std::println("{} ready", name_);
}
~Stage() { std::println("{} closed", name_); }
private:
std::string name_;
};
class Pipeline {
public:
Pipeline() : reader_("reader"), writer_("writer") {
std::println("pipeline ready");
}
~Pipeline() { std::println("pipeline closing"); }
private:
Stage reader_;
Stage writer_;
};
int main() {
Pipeline pipeline;
std::println("working");
}Output
reader ready writer ready pipeline ready working pipeline closing writer closed reader closed
Building a Pipeline creates its members first, in the order they’re declared, and then runs the constructor body. So when pipeline ready prints, both stages exist and can be used. Destroying it runs in exactly the reverse order: the destructor body first, while the members still exist, then the members, last declared first. That’s the same newest-first rule you saw for local variables in Stack, heap and lifetime.
~Pipeline() never mentions reader_ or writer_. Destroying the members is automatic; a destructor body only handles what the members can’t handle themselves.
Members are created in declaration order
The order in the initializer list doesn’t change the order members are created in: it’s always the declaration order. That matters when one member’s starting value uses another member. Here values_ is declared first, so it’s created first, from width_, which has no value yet. GCC and Clang warn when the list’s order differs from the declarations (-Wreorder, part of -Wall), and with warnings as errors it doesn’t compile:
#include <cstddef>
#include <vector>
class Window {
public:
explicit Window(std::size_t width) : width_(width), values_(width_) {}
private:
std::vector<float> values_;
std::size_t width_;
};
int main() {
Window window(4);
}The compiler rejects this
main.cpp: In constructor ‘Window::Window(std::size_t)’:
main.cpp:10:17: error: ‘Window::width_’ will be initialized after [-Werror=reorder]
10 | std::size_t width_;
| ^~~~~~
compilation terminated due to -fmax-errors=1.The fix is to write the list in declaration order, and to build members from the constructor’s parameters rather than from other members: : values_(width), width_(width).
Undefined behaviorWhy the order warning matters
Without the warning, this compiles, and values_ is built from whatever bytes width_ happens to hold. That’s undefined behavior: the vector might get 0 elements, or try to allocate billions.
The rule of zero
Buffer in Dynamic memory and RAII owned a raw pointer, so it needed a destructor to free it, and copying a Buffer freed the same memory twice. The fix offered there was to hold a std::vector<float> instead. That’s the rule of zero: if every member cleans up after itself, write no destructor, and the class gets everything right without one.
#include <cstddef>
#include <print>
#include <vector>
class Image {
public:
Image(std::size_t width, std::size_t height)
: width_(width), pixels_(width * height) {}
void set(std::size_t x, std::size_t y, float value) {
pixels_[y * width_ + x] = value;
}
float get(std::size_t x, std::size_t y) const {
return pixels_[y * width_ + x];
}
private:
std::size_t width_;
std::vector<float> pixels_;
};
int main() {
Image image(3, 2);
image.set(1, 1, 0.5f);
Image copy = image;
copy.set(1, 1, 0.9f);
std::println("{} {}", image.get(1, 1), copy.get(1, 1));
}Output
0.5 0.9
Image has no destructor, yet nothing leaks: the compiler writes one for it, which destroys each member, and pixels_’s destructor frees the pixels. Copying an Image copies each member, so the copy gets its own pixels, and changing one doesn’t touch the other. The next lesson, Copy and move, shows how copying works and how to control it.
The same goes for a member that owns one heap object through a smart pointer:
#include <memory>
#include <print>
struct Weights {
~Weights() { std::println("weights freed"); }
};
class Model {
public:
Model() : weights_(std::make_unique<Weights>()) {}
private:
std::unique_ptr<Weights> weights_;
};
int main() {
{
Model model;
std::println("model ready");
}
std::println("done");
}Output
model ready weights freed done
Model writes no destructor, and the weights are still freed at the closing brace. A Model can’t be copied, because a std::unique_ptr can’t; moving one is the subject of the next lesson.
Which one should I use?
| What | When | Why | How |
|---|---|---|---|
| Default member initializer | A member has a sensible starting value most of the time: a count of 0, a default threshold. | Every constructor gets it for free, and no member is ever left uninitialized. | int passed_ = 0; |
| Member initializer list | The value comes from a constructor argument. | The member is created with its value, once. It’s the only way for const and reference members. | : start_(start), end_(end) |
| Constructor body | Work that needs every member ready: checking or fixing values, logging. | The members already exist when it runs. | if (start_ > end_) { … } |
| Delegating constructor | Several constructors share the same setup. | The setup and its checks are written once. | Interval(int p) : Interval(p, p + 1) {} |
explicit | Any constructor callable with one argument. | No silent conversions from that argument’s type. | explicit Interval(int position); |
Rule of thumb: give every member a default, set the rest in the initializer list, and write a destructor only when the flow below says so.
Does every member clean up after itself (numbers,
std::string,std::vector,std::unique_ptr, other classes like these)?YesNoNo destructor: the rule of zero.
Could a standard type own the resource instead (
std::vectorfor an array,std::unique_ptrfor one heap object)?YesNoUse that type as the member, and write no destructor.
Otherwise: Write a destructor that frees the resource, and also decide how copying and moving work: the next lesson covers this rule of five.
Under the hood
A constructor doesn’t get memory for the object. The memory already exists: a slot in the stack frame for a local variable, or a heap block that std::make_unique asked for. The constructor’s job is to fill that memory in. Likewise, a destructor doesn’t give the object’s own memory back; it cleans up what the members point to, and then the stack frame or the heap block goes away as usual.
When you don’t write them, the compiler writes the special member functions for you:
- A default constructor, if you wrote no constructor at all. It creates each member with its default member initializer, or else the member’s own default constructor. An
intwith neither is left uninitialized. - A destructor, if you didn’t write one. It destroys each member in reverse order.
- Functions to copy and to move the object, member by member, unless you’ve declared some of them yourself. The next lesson covers them and the rules.
After Image copy = image;, there are two Image objects of 32 bytes each on the stack (on this platform: an 8-byte width_ and a 24-byte std::vector), and each pixels_ owns its own heap block:
When main ends, copy is destroyed first, then image. Each compiler-written destructor destroys pixels_, which frees its own block, once.
Common pitfalls
No default constructor after you write one
The compiler writes a default constructor only if you write no constructor at all. Once a class has Interval(int start, int end), an Interval with no arguments doesn’t compile:
class Interval {
public:
Interval(int start, int end) : start_(start), end_(end) {}
private:
int start_;
int end_;
};
int main() {
Interval empty;
}The compiler rejects this
main.cpp: In function ‘int main()’:
main.cpp:11:14: error: no matching function for call to ‘Interval::Interval()’
11 | Interval empty;
| ^~~~~
main.cpp:11:14: note: there are 3 candidates
main.cpp:3:5: note: candidate 1: ‘Interval::Interval(int, int)’
3 | Interval(int start, int end) : start_(start), end_(end) {}
| ^~~~~~~~
main.cpp:3:5: note: candidate expects 2 arguments, 0 provided
main.cpp:1:7: note: candidate 2: ‘constexpr Interval::Interval(const Interval&)’
1 | class Interval {
| ^~~~~~~~
main.cpp:1:7: note: candidate expects 1 argument, 0 provided
main.cpp:1:7: note: candidate 3: ‘constexpr Interval::Interval(Interval&&)’
main.cpp:1:7: note: candidate expects 1 argument, 0 providedEither always pass the arguments, or add a default constructor such as Interval() : Interval(0, 0) {}. A std::vector<Interval> of a given size needs one too, because it creates its elements with no arguments.
Empty parentheses don’t call the default constructor
Interval empty(); looks like a call to the default constructor, but it declares a function named empty, as Variables showed. Write Interval empty; or Interval empty{};.
Try it yourself
Try it yourself
This Matrix owns its numbers through a raw pointer and frees them in its destructor. It works as long as nobody copies it. Apply the rule of zero: replace the pointer with a std::vector<float> and remove the destructor. Then copy m, set the copy’s element (0, 0) to 9, and print both elements.
#include <cstddef>
#include <print>
class Matrix {
public:
Matrix(std::size_t rows, std::size_t cols)
: cols_(cols), data_(new float[rows * cols]{}) {}
~Matrix() { delete[] data_; }
void set(std::size_t r, std::size_t c, float value) {
data_[r * cols_ + c] = value;
}
float get(std::size_t r, std::size_t c) const {
return data_[r * cols_ + c];
}
private:
std::size_t cols_;
float* data_;
};
int main() {
Matrix m(2, 3);
m.set(0, 0, 1.0f);
std::println("{}", m.get(0, 0));
}Expected output
1 9
Show a hint
Change the member to std::vector<float> data_; and create it in the initializer list with data_(rows * cols), which makes that many floats set to 0. Delete the destructor. Then in main, write Matrix copy = m; and copy.set(0, 0, 9.0f);.
Show a solution
#include <cstddef>
#include <print>
#include <vector>
class Matrix {
public:
Matrix(std::size_t rows, std::size_t cols)
: cols_(cols), data_(rows * cols) {}
void set(std::size_t r, std::size_t c, float value) {
data_[r * cols_ + c] = value;
}
float get(std::size_t r, std::size_t c) const {
return data_[r * cols_ + c];
}
private:
std::size_t cols_;
std::vector<float> data_;
};
int main() {
Matrix m(2, 3);
m.set(0, 0, 1.0f);
Matrix copy = m;
copy.set(0, 0, 9.0f);
std::println("{} {}", m.get(0, 0), copy.get(0, 0));
}The vector owns the floats, so the compiler-written destructor frees them and you need none: the rule of zero. Copying a Matrix now copies the vector, and the copy gets its own floats. With the raw pointer and destructor, the same copy would have freed one block twice.
Saved in this browser only.