C++ Constructors
A constructor is a special method that runs automatically when an object is created. Its job is to put the new object into a valid state. A constructor has the same name as the class and no return type — not even void.
A basic constructor
#include <iostream>
#include <string>
using namespace std;
class Book {
public:
string title;
int pages;
Book(string t, int p) {
title = t;
pages = p;
cout << "Created \"" << title << "\"\n";
}
};
int main() {
Book a("Dracula", 418);
Book b{"Emma", 474};
cout << a.title << " has " << a.pages << " pages\n";
cout << b.title << " has " << b.pages << " pages\n";
}Created "Dracula"
Created "Emma"
Dracula has 418 pages
Emma has 474 pages
Once a class declares a constructor with parameters, you can no longer write Book c; — the compiler insists on the required arguments. That is a feature: it is impossible to create a book without a title.
Member initializer lists
The preferred way to initialise members is a member initializer list after a colon. It initialises members directly instead of first default-constructing and then assigning them, and it is the only way to initialise const members and references:
#include <iostream>
#include <string>
using namespace std;
class Student {
public:
Student(string name, int year)
: name(std::move(name)), year(year), id(nextId++) {}
void print() const {
cout << "#" << id << " " << name << " (year " << year << ")\n";
}
private:
string name;
int year;
const int id; // const: must be set in the initializer list
inline static int nextId = 1;
};
int main() {
Student s1("Ana", 2);
Student s2("Bilal", 1);
s1.print();
s2.print();
}#1 Ana (year 2)
#2 Bilal (year 1)
Note: Members are initialised in the order they are declared in the class, not the order you write them in the list. Keep both orders the same to avoid surprises (
-Wallwarns about mismatches).
Overloaded and default constructors
A class can have several constructors with different parameters. A constructor with no parameters is the default constructor. Constructors can also delegate to each other:
#include <iostream>
using namespace std;
class Time {
public:
Time() : Time(0, 0) {} // default -> delegates
Time(int h, int m) : hours(h), minutes(m) {}
explicit Time(int totalMinutes) : Time(totalMinutes / 60, totalMinutes % 60) {}
void print() const {
cout << (hours < 10 ? "0" : "") << hours << ":"
<< (minutes < 10 ? "0" : "") << minutes << "\n";
}
private:
int hours;
int minutes;
};
int main() {
Time midnight;
Time lunch(12, 30);
Time film(135);
midnight.print();
lunch.print();
film.print();
}00:00
12:30
02:15
explicit stops the compiler from silently converting an int into a Time (for example when passing 135 to a function that expects a Time). Mark single-argument constructors explicit unless you really want that conversion.
Destructors
The counterpart of a constructor is the destructor, named ~ClassName(). It runs automatically when an object is destroyed — at the end of its scope, or on delete. Destructors release resources: close files, free memory, unlock mutexes. Objects are destroyed in reverse order of creation:
#include <iostream>
#include <string>
using namespace std;
class Tracer {
public:
Tracer(string n) : name(n) { cout << "construct " << name << "\n"; }
~Tracer() { cout << "destroy " << name << "\n"; }
private:
string name;
};
int main() {
Tracer a("A");
{
Tracer b("B");
Tracer c("C");
cout << "leaving inner block\n";
}
cout << "leaving main\n";
}construct A
construct B
construct C
leaving inner block
destroy C
destroy B
leaving main
destroy A
This automatic, predictable cleanup is called RAII and is one of C++'s most important ideas.
Copy constructor
When an object is created as a copy of another (Book c = a;), the copy constructor runs. The compiler generates one that copies every member, which is usually exactly right. You write your own only when the class manages a resource such as raw memory — a topic revisited in the Move Semantics lesson.
Test yourself
What is the return type of a constructor?
- void
- The class type
- int
- Constructors have no return type
Which members MUST be initialised in a member initializer list?
- static members
- const members and references
- public members
- string members
In which order are local objects destroyed when a scope ends?
- In creation order
- In reverse creation order
- Alphabetically
- Unspecified