Lesson 11 of 45 · C++
Lesson 19: Constructors and Destructors
Duration: 11 min
Lesson 11 of 45 · C++
Duration: 11 min
cpp\nclass Resource {\n int* data;\npublic:\n // Default constructor\n Resource() : data(new int[10]()) {\n std::cout << \"Resource default‑constructed\" << '\\n';\n }\n // Parameterised constructor\n explicit Resource(std::size_t n) : data(new int[n]()) {\n std::cout << \"Resource of size \" << n << \" constructed\" << '\\n';\n }\n // Copy constructor\n Resource(const Resource& other) {\n // deep copy\n std::size_t n = 10; // assume same size for illustration\n data = new int[n];\n std::copy(other.data, other.data + n, data);\n std::cout << \"Resource copy‑constructed\" << '\\n';\n }\n // Move constructor\n Resource(Resource&& other) noexcept : data(other.data) {\n other.data = nullptr;\n std::cout << \"Resource move‑constructed\" << '\\n';\n }\n // Destructor\n ~Resource() {\n delete[] data;\n std::cout << \"Resource destroyed\" << '\\n';\n }\n};\n\nint main() {\n Resource r1(5); // parameterised\n Resource r2 = r1; // copy\n Resource r3 = std::move(r1); // move\n return 0; // r2 and r3 go out of scope, destructor called\n}\n\n\n> Tip: Use RAII – acquire resources in the constructor and release them in the destructor.\n\n---\n\n