Skip to content

Module 5 · Classes and Objects — topic 2 of 5

Constructors

Constructors initialise objects. Learn default, parameterised and delegating constructors, member initialiser lists, explicit, and the copy constructor.

Beginner 16 min read·Lesson 18 of 40 in C++ Programming

Learning objectives

  • Write default and parameterised constructors with initialiser lists
  • Use explicit to prevent unwanted conversions
  • Explain when the copy constructor runs

Definition

A constructor is a special member function with the class's name and no return type that runs automatically when an object is created, establishing its initial state.

Introduction

Without a constructor an object's members may hold garbage. A constructor guarantees every object starts valid: a Date is always a real date, a Fraction never has a zero denominator.

Why it matters

Constructors establish class invariants — the rules that must always be true for an object.

Initialiser lists are required for const members, references and members without default constructors.

Detailed explanation

Default constructor: takes no arguments. If you write no constructors at all, the compiler generates one (members of class type are default-constructed; built-ins keep their default member initialisers or are left uninitialised).

Member initialiser list: Point(int x, int y) : x_(x), y_(y) {} initialises members directly instead of assigning afterwards. Members are initialised in declaration order, not list order.

explicit stops a single-argument constructor from being used for implicit conversions (Fraction f = 3;).

Copy constructor T(const T&) creates an object as a copy; it runs when passing by value, returning by value (unless elided) or writing T b = a;.

Delegating constructor: Fraction() : Fraction(0, 1) {} reuses another constructor.

Syntax

C++
class Fraction {
public:
Fraction() : Fraction(0, 1) {} // delegating
explicit Fraction(int whole) : Fraction(whole, 1) {}
Fraction(int num, int den); // validating constructor
private:
int num_, den_;
};
  • Constructors have no return type.
  • Use = default to request the compiler-generated version explicitly.
  • Throw an exception if arguments are invalid.

Code examples

Default and parameterised

C++
#include <iostream>
#include <string>
class Book {
public:
Book() : title_("Untitled"), pages_(0) {}
Book(std::string title, int pages) : title_(std::move(title)), pages_(pages) {}
void print() const { std::cout << title_ << " (" << pages_ << " pages)\n"; }
private:
std::string title_;
int pages_;
};
int main() {
Book a;
Book b("Clean Code", 464);
a.print();
b.print();
return 0;
}
Output
Untitled (0 pages)
Clean Code (464 pages)

Initialisation order follows declaration order

C++
#include <iostream>
class Pair {
public:
Pair(int v) : second_(v * 2), first_(v) {} // list order doesn't matter
void show() const { std::cout << first_ << ' ' << second_ << '\n'; }
private:
int first_;
int second_;
};
int main() {
Pair p(5);
p.show();
return 0;
}
Output
5 10

Compilers warn with -Wreorder when the list order differs from declaration order.

More examples

A validating Fraction class

C++
#include <iostream>
#include <numeric>
#include <stdexcept>
class Fraction {
public:
Fraction() : Fraction(0, 1) {}
explicit Fraction(int whole) : Fraction(whole, 1) {}
Fraction(int num, int den) {
if (den == 0) throw std::invalid_argument("denominator is zero");
if (den < 0) { num = -num; den = -den; }
int g = std::gcd(num, den);
num_ = num / (g ? g : 1);
den_ = den / (g ? g : 1);
}
Fraction(const Fraction& other) : num_(other.num_), den_(other.den_) { ++copies; }
void print() const { std::cout << num_ << '/' << den_ << '\n'; }
static int copies;
private:
int num_ = 0, den_ = 1;
};
int Fraction::copies = 0;
int main() {
Fraction a(6, -8), b(5), c;
a.print(); b.print(); c.print();
Fraction d = a; // copy constructor
d.print();
std::cout << "copies: " << Fraction::copies << '\n';
try { Fraction bad(1, 0); } catch (const std::invalid_argument& e) { std::cout << "error: " << e.what() << '\n'; }
return 0;
}
Output
-3/4
5/1
0/1
-3/4
copies: 1
error: denominator is zero

Step-by-step explanation

  • Fraction(6, -8) moves the sign to the numerator and reduces by the gcd 2: −3/4.
  • Fraction(5) delegates to (5, 1); Fraction() to (0, 1).
  • Fraction d = a; calls the user-written copy constructor, incrementing copies.
  • A zero denominator throws, so an invalid Fraction can never exist.

Expected output

Running “A validating Fraction class” prints exactly:

TextOutput
-3/4
5/1
0/1
-3/4
copies: 1
error: denominator is zero

Practical applications

  • std::string("text") and std::vector<int>(10, 0) are constructor calls.
  • Database connection classes open the connection in the constructor.
  • Value types like Date and Money validate in their constructors.

Best practices

  • Initialise every member in the initialiser list or with a default member initialiser.
  • Mark single-argument constructors explicit.
  • Throw from a constructor when arguments are invalid.

Common mistakes

Assigning instead of initialising const members

Avoid

class C { const int id; public: C(int v) { id = v; } };

Prefer

class C { const int id; public: C(int v) : id(v) {} };

const and reference members must be initialised in the initialiser list.

Most vexing parse

Avoid

Book b(); // declares a function!

Prefer

Book b; // or Book b{};

Empty parentheses declare a function returning Book; use no parentheses or braces.

Important notes

  • If you define any constructor, the compiler no longer generates the default constructor; add = default if you need it.
  • Copy elision means T x = make(); usually calls no copy constructor at all (guaranteed in C++17 for prvalues).

Key takeaways

  • Constructors initialise objects and enforce invariants.
  • Use initialiser lists; members initialise in declaration order.
  • explicit prevents implicit conversions; copy constructors copy.

Try it yourself

  1. 1
    Write a Date class whose constructor rejects invalid dates such as 31/02/2026.
  2. 2
    Add a constructor to Rectangle that creates a square from one side length, using delegation.

Finished reading? Mark it complete to update your dashboard.

Suggested practice

9 questions test this exact topic. Answers and explanations are revealed after you submit.

  • BeginnerWhen does a constructor run?
  • BeginnerWhat is printed?
  • BeginnerWhy is `Book b();` a problem?
Practise this topic