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
  • Teach on BraveProgrammer

© 2026 BraveProgrammer. All rights reserved.

Lesson 19: Constructors and Destructors | C++ Course lesson | BraveProgrammer
  1. Courses
  2. /
  3. C++ Course

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.

4 points
  • Constructor declaration vs. definition
  • Default arguments
  • Function prototypes
  • Inline functions

Constructors and Destructors

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.


Example: Various constructors and a destructor

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.


Note

Mark destructors noexcept (default) to guarantee exception‑safety during stack unwinding.
Make it stickPractice what you've learned1 quiz · 2 practical tests · Optional activities from C++ CourseBrowse activities
Previous lessonLesson 18: Classes and ObjectsContinue to lesson 20Lesson 20: Copy Constructor, Assignment Operator, Rule of Three/FiveBack to C++ Course curriculum