Explain it simply
Explain it simply
A car factory never hands a customer a car without its wheels; every part is in place the moment the car rolls out. A constructor is that final assembly step. It is a special member function that C++ calls automatically at the moment an object is created.
A constructor has the same name as the class and no return type at all, not even void. If it takes parameters, as in Car(std::string brand, int year), the only way to create a Car is something like Car myCar("Toyota", 2024);, and the compiler refuses to build a Car without a brand and a year.
Problem → Why → Solution
The problem: half-built objects
Without a constructor you create the object first and fill in its fields one by one afterwards. Forget one field and the object looks complete while carrying garbage inside. The program below compiles and runs, yet the year it prints can be a different random number on every run.
#include <iostream>
#include <string>
class Car {
public:
std::string brand;
int year;
};
int main() {
Car car;
car.brand = "Toyota";
// forgot: car.year = 2024;
std::cout << car.brand << " - " << car.year << '\n'; // garbage year
}Why doesn't the compiler stop this?
Car car; is perfectly legal, and the compiler has no idea which fields must be filled in or when. The job of filling them is scattered across every place that creates a Car. A constructor gathers that job into one place: without the required arguments the object cannot be created at all, so a half-built object becomes impossible.
Core concept: the initializer list runs, then the body
Running a constructor happens in two phases. First every member is initialized: with the value written in the member initializer list, such as : brand(b), year(y), or, for members not listed there, with their default member initializer if they have one, or default construction otherwise. Only then does the body between the braces run. Writing brand = b; in the body is not initialization; it assigns to a member that was already constructed as an empty string.
For a std::string member, assigning in the body does the work twice (construct, then replace) but still gives the right result. A const member, a reference member or a member whose type has no default constructor can only be initialized, never assigned, so for those the initializer list is mandatory. Make the initializer list your normal habit and keep the body for real work such as validation or calculation.
One rule matters a lot: the order of initialization. Members are initialized in the order they are declared in the class, not in the order you list them in the initializer list. If one member's initializer reads a member declared later, it reads garbage, because that member is not initialized yet. With -Wall, g++ flags the mismatch as a -Wreorder warning, so always write the initializer list in declaration order.
As soon as you write any constructor yourself, the compiler stops generating the parameterless default constructor. If Car car; should still work, ask for it back with Car() = default;, or forward the work with a delegating constructor such as Car() : Car("Unknown", 2000) {}.
| Kind | Example | Use it when |
|---|---|---|
| Default | Car() = default; | Every member has a sensible default |
| Parameterized | Car(std::string b, int y) | The object needs data to exist |
| Delegating | Car() : Car("Unknown", 2000) {} | You want to reuse another constructor |
| explicit single-argument | explicit Car(std::string b) | You want to block implicit conversion |
- Pick the constructor matching args
- Init members in declaration order
- Run the constructor body
- The object is ready to use
By the time the body runs, every member already exists, which is why initialization belongs in the initializer list.
General pattern
class ClassName {
public:
ClassName(TypeA a, TypeB b) : first(a), second(b) {} // initializer list
ClassName() : ClassName(defaultA, defaultB) {} // delegating
explicit ClassName(TypeA a) : first(a) {} // no implicit conversion
ClassName(const ClassName&) = delete; // forbid copying
TypeA first; // initialized 1st: declaration order wins
TypeB second = defaultValue; // default member initializer
};A constructor is named after its class and has no return type. The initializer list after : initializes members directly. One constructor may delegate to another, and marking single-argument constructors explicit stops silent type conversions. = delete switches off a function the compiler would otherwise generate.
Example: the Car constructor
This example shows a constructor's basic job: the single line Car myCar("Toyota", 2024); creates the object and fills in both fields. Notice that the constructor assigns inside its body; the breakdown below shows how the same constructor looks with an initializer list.
#include <iostream>
#include <string>
using namespace std;
class Car {
public:
string brand;
int year;
Car(string b, int y) {
brand = b;
year = y;
}
void show() {
cout << brand << " - " << year;
}
};
int main() {
Car myCar("Toyota", 2024);
myCar.show();
return 0;
}Code breakdown
- Line 10
Car(string b, int y) {Same name as the class and no return type, so this is a constructor. Because it is the only one, Car c; with no arguments no longer compiles.
- Lines 11-12
brand = b;When this runs, brand has already been constructed as an empty string, so this is a second step, an assignment. Car(string b, int y) : brand(b), year(y) {} would initialize it in one go.
- Line 21
Car myCar("Toyota", 2024);The line that creates the object. "Toyota" and 2024 arrive as the constructor's b and y, and when the constructor finishes, myCar is ready to use.
- Line 16
cout << brand << " - " << year;show() can only be called after the constructor has filled both fields, so no garbage value can appear. The output is Toyota - 2024.
Toyota - 2024Members that require the initializer list
In the Car below, vin (the vehicle identification number) is const because a car's VIN should never change. A const member cannot be assigned in the body, so the initializer list is the only place to give it a value. mileage is not in the initializer list at all, yet it starts at 0 thanks to its default member initializer.
#include <iostream>
#include <string>
class Car {
public:
const std::string vin; // const: can be initialized, never assigned
std::string brand;
int year;
int mileage = 0; // default member initializer
Car(std::string v, std::string b, int y) : vin(v), brand(b), year(y) {}
void show() const {
std::cout << brand << " " << year << " [" << vin << "] "
<< mileage << " km\n";
}
};
int main() {
Car car("JT123", "Toyota", 2024);
car.mileage = 1500;
car.show();
// car.vin = "X999"; would not compile: vin is const
}The program prints "Toyota 2024 [JT123] 1500 km". The initializer list names vin, brand and year in the same order as their declarations, so there is no -Wreorder warning.
Delegating constructors, explicit and = default
Rectangle has three constructors. Rectangle() = default; asks for the compiler-generated default constructor back, and width and height get 1 from their default member initializers. Rectangle(int side) does not repeat any logic; it delegates to Rectangle(side, side). Because it is explicit, writing printArea(5) does not silently build a Rectangle from the int 5; it is a compile error.
#include <iostream>
class Rectangle {
public:
Rectangle() = default; // 1 x 1
Rectangle(int w, int h) : width(w), height(h) {}
explicit Rectangle(int side) : Rectangle(side, side) {} // delegating
int area() const { return width * height; }
int width = 1;
int height = 1;
};
void printArea(const Rectangle& r) { std::cout << "area " << r.area() << '\n'; }
int main() {
Rectangle unit;
Rectangle wide(4, 2);
Rectangle square(3); // runs Rectangle(3, 3) first
printArea(unit);
printArea(wide);
printArea(square);
// printArea(5); error: Rectangle(int) is explicit
}The output is area 1, area 8 and area 9. = delete is the opposite tool: it switches off a function the compiler would generate. std::unique_ptr from lesson 16 deletes its copy constructor, which is why trying to copy one is a compile error and ownership stays unique.
In real projects
Where this shows up in real projects
The standard library's RAII types lean on constructors heavily. std::ifstream file("data.txt"); opens the file inside its constructor, and std::lock_guard lock(m); locks the mutex inside its constructor. The resource is held for as long as the object exists and the destructor releases it, which removes a whole family of "opened it but forgot to close it" bugs.
Application code also takes whatever a class needs to work as constructor parameters, as in OrderService(Database& db, Logger& log). Making dependencies visible like this lets a test pass in a fake database. The C++ Core Guidelines recommend making single-argument constructors explicit by default and writing initializer lists in member declaration order, and most teams' style guides carry the same rules.
Common mistakes
Common mistakes
1. Trusting the order of the initializer list
In class Range { public: int width; int start; int end; Range(int s, int e) : start(s), end(e), width(end - start) {} };, width is declared first, so it is computed before start and end exist and gets garbage. g++ warns "'Range::end' will be initialized after [-Wreorder]" and "member 'Range::end' is used uninitialized". Declare width last, or compute it from the parameters as width(e - s).
2. Giving a constructor a return type
Writing void Car(std::string b) { ... } makes g++ report "return type specification for constructor invalid". A constructor builds the object and returns nothing, so it takes no return type at all.
3. Losing the default constructor
Once Car(std::string b, int y) exists, Car c; or Car garage[3]; fails with "no matching function for call to 'Car::Car()'". If a default Car makes sense, give the members defaults and add Car() = default;. If it does not, the error is protecting you.
4. Writing Car c();
Car c(); declares a function c that returns a Car, not an object (the "most vexing parse"). g++ warns "empty parentheses were disambiguated as a function declaration [-Wvexing-parse]", and using c.brand later is an error. Write Car c; or Car c{}; instead.
Best practices
Best practices
- Initialize members in the initializer list instead of assigning in the body, and list them in declaration order.
- Give constant defaults with default member initializers such as int mileage = 0; instead of repeating them in every constructor.
- Make every constructor callable with one argument explicit, unless you genuinely want the implicit conversion.
- When constructors share setup code, keep it in one place with a delegating constructor.
Mini challenge
Mini challenge: a Fraction class
Write a Fraction class with three constructors whose objects are always in lowest terms from the moment they are created.
- Declare numerator before denominator, and have Fraction(int n, int d) use an initializer list in that order
- The constructor body makes the denominator positive and reduces with std::gcd
- explicit Fraction(int whole) and Fraction() delegate to Fraction(int, int)
- Print Fraction(6, 8), Fraction(1, -2), Fraction(5) and Fraction()
#include <iostream>
#include <numeric> // std::gcd
class Fraction {
public:
int numerator;
int denominator;
Fraction(int n, int d) /* TODO: initializer list */ {
// TODO: move a negative sign from the denominator to the numerator
// TODO: divide both by their greatest common divisor
}
// TODO: explicit Fraction(int whole) that delegates (whole / 1)
// TODO: Fraction() that delegates (0 / 1)
void print() const {
// TODO: print "numerator/denominator" and a newline
}
};
int main() {
// TODO: build and print 6/8, 1/-2, the whole number 5 and a default Fraction
}Expected: 3/4 -1/2 5/1 0/1
Show hint
std::gcd works on the absolute values of its arguments, so a negative numerator is fine, and gcd(0, 1) is 1. A delegating constructor's initializer list may contain only the target constructor, as in Fraction(int whole) : Fraction(whole, 1) {}.
Show solution
#include <iostream>
#include <numeric>
class Fraction {
public:
int numerator;
int denominator;
Fraction(int n, int d) : numerator(n), denominator(d) {
if (denominator < 0) {
numerator = -numerator;
denominator = -denominator;
}
int g = std::gcd(numerator, denominator);
if (g != 0) {
numerator /= g;
denominator /= g;
}
}
explicit Fraction(int whole) : Fraction(whole, 1) {}
Fraction() : Fraction(0, 1) {}
void print() const { std::cout << numerator << "/" << denominator << '\n'; }
};
int main() {
Fraction(6, 8).print();
Fraction(1, -2).print();
Fraction(5).print();
Fraction zero;
zero.print();
}Quick quiz 1 / 3
Quick quiz 2 / 3
Quick quiz 3 / 3
What to remember
- A constructor runs automatically when an object is created; it is named after the class and has no return type.
- The member initializer list initializes members before the body runs, and const or reference members require it.
- Members are initialized in declaration order, so write the list in that order (-Wreorder).
- Delegating constructors reuse logic, explicit blocks implicit conversions, and = default / = delete control generated functions.
The Current ISO C++ Standard (C++23) — Standard C++ Foundation