Lesson 19 of 45
C++Lesson 19: Constructors and Destructors
11 min
Course progress42%
What you'll learn
Keep these ideas in mind as you work through the lesson.
Lesson 19 of 45
C++11 min
Keep these ideas in mind as you work through the lesson.
A constructor creates and initialises an object. A destructor cleans up resources just before the object’s lifetime ends. C++ supports default, parameterised, copy, move, and delegating constructors.
class Resource {
int* data;
public:
// Default constructor
Resource() : data(new int[10]()) {
std::cout << \"Resource default‑constructed\" << '\
';
}
// Parameterised constructor
explicit Resource(std::size_t n) : data(new int[n]()) {
std::cout << \"Resource of size \" << n << \" constructed\" << '\
';
}
// Copy constructor
Resource(const Resource& other) {
// deep copy
std::size_t n = 10; // assume same size for illustration
data = new int[n];
std::copy(other.data, other.data + n, data);
std::cout << \"Resource copy‑constructed\" << '\
';
}
// Move constructor
Resource(Resource&& other) noexcept : data(other.data) {
other.data = nullptr;
std::cout << \"Resource move‑constructed\" << '\
';
}
// Destructor
~Resource() {
delete[] data;
std::cout << \"Resource destroyed\" << '\
';
}
};
int main() {
Resource r1(5); // parameterised
Resource r2 = r1; // copy
Resource r3 = std::move(r1); // move
return 0; // r2 and r3 go out of scope, destructor called
}
Tip: Use RAII – acquire resources in the constructor and release them in the destructor.