The Analogy: The Factory Setup Line
When a kettle comes off the production line it does not arrive as a loose pile of parts for you to assemble. The last station on the line fits the element, fills in the serial number and sets the thermostat to a safe default. By the time the box is sealed, the kettle works.
A constructor is that last station. It runs automatically the instant an object is created, and its one job is to leave the object in a valid state — every member set, every rule of the class already true. Get that right and the rest of the class never has to ask "has this been initialised yet?"
The matching station at the other end of the object's life is the destructor, which runs automatically when the object goes out of scope and hands back anything the constructor acquired.
Syntax or Core Structure
A constructor has the class's name and no return type. It may be overloaded like any other function.
#include <iostream>
#include <string>
class Account {
std::string owner;
double balance;
int transactions;
public:
// Default constructor -- no arguments.
Account() : owner("unnamed"), balance(0.0), transactions(0) {}
// Parameterised, using a member initialiser list (after the colon).
Account(std::string name, double opening)
: owner(std::move(name)), balance(opening), transactions(0) {}
// Delegating: reuse another constructor rather than repeat yourself.
explicit Account(std::string name) : Account(std::move(name), 0.0) {}
// Destructor -- runs automatically at end of scope.
~Account() {
std::cout << "closing " << owner << "\n";
}
void deposit(double amount) { balance += amount; ++transactions; }
double getBalance() const { return balance; }
const std::string& getOwner() const { return owner; }
};
int main() {
Account a; // default constructor
Account b{"Ada", 250.0}; // two-argument constructor
Account c{"Grace"}; // one-argument -> delegates
b.deposit(50.0);
std::cout << b.getOwner() << " " << b.getBalance() << "\n"; // Ada 300
std::cout << c.getBalance() << "\n"; // 0
return 0; // destructors run here, in reverse order
}
The output ends with closing Grace, closing Ada, closing unnamed — objects are destroyed in the reverse of their construction order.
Technical Depth: Initialise, Do Not Assign
The member initialiser list is not a style choice
These two constructors look equivalent. They are not.
class Bad {
std::string name;
public:
Bad(const std::string& n) { name = n; } // construct empty, THEN assign
};
class Good {
std::string name;
public:
Good(const std::string& n) : name(n) {} // construct directly
};
Bad builds an empty std::string, then throws it away and copies n over it — two operations where one would do. For some members assignment is not merely wasteful but impossible:
class Config {
const int version; // const: can only be initialised
std::string& logSink; // reference: MUST be initialised
public:
Config(int v, std::string& sink) : version(v), logSink(sink) {}
// A body assignment 'version = v;' would not compile.
};
const members, reference members, and members of a class with no default constructor can only be set in the initialiser list.
Members initialise in declaration order, not list order
class Range {
int low;
int high;
int span;
public:
Range(int a, int b) : span(b - a), low(a), high(b) {} // MISLEADING
};
The compiler ignores the list's order and follows the declaration order: low, then high, then span. So span is computed from a and b — fine here — but had it been written span(high - low) it would read two uninitialised members. Compile with -Wreorder and the compiler warns whenever the two orders disagree.
Default member initialisers plus constructors
You can combine both: declare defaults at the member, and override only what a constructor needs.
class Session {
std::string user{"guest"};
int timeout{300};
bool active{false};
public:
Session() = default; // defaults are enough
explicit Session(std::string name) : user(std::move(name)) {}
// timeout and active still get 300 and false
};
This is the least error-prone pattern: add a member later and every constructor already initialises it.
The compiler-generated constructors
If you write no constructors at all, you get a default one for free. Declare any constructor and the free default disappears:
class Widget {
public:
Widget(int n); // now 'Widget w;' does not compile
};
Ask for it back with = default, or forbid it with = delete:
class Widget {
public:
Widget() = default;
Widget(int n);
};
class NoDefault {
public:
NoDefault() = delete; // must always be given arguments
NoDefault(int n);
};
explicit, and why single-argument constructors need it
A one-argument constructor doubles as an implicit conversion unless you stop it:
class Metres {
public:
Metres(double v); // no 'explicit'
};
void draw(Metres length);
draw(3.5); // compiles! double silently became Metres
That is rarely what you want. explicit Metres(double v); forces draw(Metres{3.5}) and makes the conversion visible. Mark single-argument constructors explicit by default.
The brace-versus-parenthesis trap
std::vector<int> a(10, 2); // ten elements, each 2
std::vector<int> b{10, 2}; // TWO elements: 10 and 2
Braces prefer an initializer_list constructor when one exists. Braces are still the better default — they reject narrowing conversions and avoid the parse below — but know the exception for containers.
The most vexing parse
Account a(); // declares a FUNCTION returning Account, not an object
Account a{}; // an object, default-constructed
Account a; // also an object
Account a(); looks like a default construction and is actually a function declaration. Empty braces avoid the ambiguity entirely.
Destructors and the rule of zero
class FileHandle {
std::FILE* handle;
public:
explicit FileHandle(const char* path) : handle(std::fopen(path, "r")) {}
~FileHandle() { if (handle) { std::fclose(handle); } }
};
The destructor runs on every exit path, including an exception, which is what makes cleanup reliable. But note: if you need a custom destructor, you almost certainly also need to think about copying, or two objects will close the same file. The modern advice — the rule of zero — is to build classes from members that manage themselves (std::string, std::vector, std::unique_ptr) so you need no destructor, no copy constructor and no assignment operator at all.
| You write | You should probably also consider |
|---|---|
| Nothing (rule of zero) | Nothing — the ideal |
| A destructor | Copy constructor and copy assignment |
| A copy constructor | Copy assignment and destructor |
| A move constructor | Move assignment, and all of the above |
Real World Example: A Booking
A class that cannot be constructed in an invalid state, with a scope-based timer to show destructors firing.
#include <iostream>
#include <string>
#include <vector>
#include <stdexcept>
class Booking {
// Declaration order IS initialisation order -- keep it meaningful.
const std::string reference; // const: only settable in the list
std::string guest;
int nights;
double ratePerNight;
std::vector<std::string> extras{}; // default member initialiser
static int liveBookings;
public:
// Full constructor: validates before the object exists in a usable form.
Booking(std::string ref, std::string who, int howManyNights, double rate)
: reference(std::move(ref)),
guest(std::move(who)),
nights(howManyNights),
ratePerNight(rate)
{
if (reference.empty()) { throw std::invalid_argument("reference required"); }
if (nights < 1) { throw std::invalid_argument("nights must be >= 1"); }
if (ratePerNight < 0.0) { throw std::invalid_argument("rate must be >= 0"); }
++liveBookings;
}
// Delegating constructor: one night at a standard rate.
Booking(std::string ref, std::string who)
: Booking(std::move(ref), std::move(who), 1, 95.0) {}
// No sensible blank booking exists, so forbid one outright.
Booking() = delete;
~Booking() { --liveBookings; }
Booking& addExtra(const std::string& item) {
extras.push_back(item);
return *this;
}
double total() const {
return nights * ratePerNight + 12.50 * static_cast<double>(extras.size());
}
const std::string& ref() const { return reference; }
const std::string& who() const { return guest; }
static int live() { return liveBookings; }
};
int Booking::liveBookings = 0;
// A stack-only guard: the destructor is the whole point.
class ScopeReport {
std::string label;
public:
explicit ScopeReport(std::string what) : label(std::move(what)) {
std::cout << "-> entering " << label << "\n";
}
~ScopeReport() { std::cout << "<- leaving " << label << "\n"; }
};
int main() {
ScopeReport guard{"main"};
Booking full{"BK-1001", "Ada Lovelace", 3, 120.0};
Booking quick{"BK-1002", "Alan Turing"}; // delegates
full.addExtra("breakfast").addExtra("parking");
std::cout << full.ref() << " " << full.total() << "\n"; // 385
std::cout << quick.who() << " " << quick.total() << "\n"; // Alan Turing 95
std::cout << "Live: " << Booking::live() << "\n"; // 2
{
Booking temporary{"BK-1003", "Grace Hopper", 2, 80.0};
std::cout << "Live inside block: " << Booking::live() << "\n"; // 3
} // destructor runs here
std::cout << "Live after block: " << Booking::live() << "\n"; // 2
try {
Booking broken{"BK-1004", "Nobody", 0, 50.0}; // throws
std::cout << "never reached\n";
} catch (const std::invalid_argument& e) {
std::cout << "rejected: " << e.what() << "\n";
}
std::cout << "Live after failure: " << Booking::live() << "\n"; // still 2
// Booking blank; // won't compile: deleted
return 0;
}
The design goal is that a Booking which exists is a Booking which is valid, and every decision serves it. reference is const, so it can only be set in the member initialiser list — an assignment in the body would not compile, which is exactly the guarantee wanted for an identifier that must never change. The members are listed in the initialiser list in their declaration order, so -Wreorder stays quiet and nobody has to wonder which value is available when. Validation happens in the constructor body, after the members are initialised, because that is the earliest point at which reference.empty() can be asked; throwing there means the object never becomes visible to the caller, and note that ++liveBookings sits after the checks so a rejected booking is never counted — which is why the count is still 2 after the failure. The delegating constructor for the one-night case calls the full one instead of duplicating four assignments and three checks, so there is exactly one place where the rules live. Booking() = delete removes the blank-booking option entirely rather than inventing a meaningless default reference. std::move on the incoming strings means the caller's temporary is transferred rather than copied. And ScopeReport exists purely to make destructor timing visible: its message prints last of all, after every Booking has been destroyed, demonstrating reverse-order destruction — the same mechanism that makes the block-scoped temporary decrement the counter the moment its closing brace is reached, with no cleanup call written anywhere.
Common Mistakes
- Assigning in the constructor body instead of the initialiser list. Wasteful for strings and vectors, and impossible for
constor reference members. - Assuming the initialiser list runs in the order you wrote it. It follows declaration order. Build with
-Wreorder. - Expecting the free default constructor to survive. Declare any constructor and it vanishes; ask for it back with
= default. - Leaving a single-argument constructor non-
explicit, so unrelated values convert silently at call sites. - Writing
Account a();and getting a function declaration. UseAccount a{};. std::vector<int> v{10, 2};when you meant ten twos. Braces prefer the initialiser-list constructor.- Calling a virtual method from a constructor. The derived part does not exist yet, so the base version runs — rarely what was intended.
- Writing a destructor that frees something, but no copy constructor. Copy the object and two destructors free the same resource.
- Leaving some members uninitialised because one constructor overload forgot them. Default member initialisers prevent this permanently.
Best Practices
- Initialise every member in the member initialiser list, in declaration order, or give it a default initialiser at the point of declaration.
- Validate in the constructor body and throw on invalid input, so an existing object is always a valid object.
- Mark single-argument constructors
explicit. - Use delegating constructors so validation and defaults live in exactly one place.
- Prefer
= defaultand= deleteto hand-written empty or forbidden constructors. - Aim for the rule of zero: build from self-managing members so you need no destructor at all.
- If you do write a destructor, decide deliberately about copying and moving.
- Use braces for initialisation, remembering the container exception.
- Keep constructors cheap. Heavy work belongs in a named method the caller can choose to run.
Practice Exercises
- Three ways in: Give a
Temperatureclass a default constructor (0 C), a one-argumentexplicitconstructor, and a two-argument constructor taking a value and a unit that delegates to the first. Create one object each way and print all three. - Order matters: Write a class with members declared
int high; int low; int span;and an initialiser list: span(high - low), high(b), low(a). Compile withg++ -Wall -Wreorder, paste the warning and the wrong value ofspaninto a comment, then fix it by reordering the declarations. - Watch them die: Create three objects of a class whose destructor prints its name — two at function scope and one inside an inner block — and predict the exact output order before running it. Then throw an exception after the second object is created and confirm which destructors still run.