Skip to main content
Brave Programmer Logo

BraveProgrammer

BraveProgrammer

HomeProjectsBlogsCoursesLessonsAbout

Site footer

BraveProgrammer

Free coding courses, practical tutorials, and real projects from BraveProgrammer. Learn web development with React, Next.js, and TypeScript.

Navigation

  • Home
  • Projects
  • Blogs
  • Courses

Resources

  • About
  • Lessons

© 2026 BraveProgrammer. All rights reserved.

  1. Courses
  2. /
  3. C++ Course

Lesson 11 of 45 · C++

Lesson 19: Constructors and Destructors

Duration: 11 min

Constructors and Destructors\n\nA 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.\n\n---\n\n## Example: Various constructors and a destructor\ncpp\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

Note

Mark destructors noexcept (default) to guarantee exception‑safety during stack unwinding.

Previous: Lesson 18: Classes and ObjectsNext: Lesson 2: Setting Up Development Environment