C++ Constructors and Destructors
C++ constructors are special member functions that run automatically when an object is created, and destructors run automatically when it is destroyed. Together they make sure objects always start valid and clean up after themselves.
Parameterized Constructor and Initializer List
A constructor has the same name as the class and no return type. The member initializer list (after the colon) initializes members directly and is the preferred style.
#include <iostream>
#include <string>
class Book {
std::string title;
int pages;
public:
Book(std::string t, int p) : title(std::move(t)), pages(p) {}
void print() const { std::cout << title << ", " << pages << " pages\n"; }
};
int main() {
Book b("Clean Code", 464);
b.print();
}Clean Code, 464 pages
Overloaded and Default Constructors
#include <iostream>
class Timer {
int seconds;
public:
Timer() : seconds(60) {} // default constructor
explicit Timer(int s) : seconds(s) {}
int get() const { return seconds; }
};
int main() {
Timer a;
Timer b(90);
std::cout << a.get() << ' ' << b.get() << '\n';
}60 90
Destructors and RAII
A destructor is named ~ClassName. Resource Acquisition Is Initialization (RAII) means acquiring a resource in the constructor and releasing it in the destructor, so cleanup happens automatically when the object goes out of scope.
#include <iostream>
class Logger {
public:
Logger() { std::cout << "open log\n"; }
~Logger() { std::cout << "close log\n"; }
};
int main() {
{
Logger log;
std::cout << "working...\n";
} // log destroyed here
std::cout << "done\n";
}open log working... close log done
Constructor Tips
- Use initializer lists for all members.
- Mark single-argument constructors explicit to prevent accidental conversions.
- Give members default values in the class when sensible.
- If you do not manage a raw resource, you usually do not need a destructor (the rule of zero).
Frequently asked questions
What is a member initializer list in C++?
It is the part after the colon in a constructor that initializes members directly, before the body runs. It is required for const and reference members and avoids double initialization.
When is a destructor called in C++?
When a local object goes out of scope, when delete is called on a heap object, or when a smart pointer releases the object.
What is RAII in C++?
RAII ties the lifetime of a resource like memory, a file or a lock to an object. The constructor acquires it and the destructor frees it, preventing leaks even when exceptions occur.