Unit 4: Object-Oriented Programming (OOP) in C++Lesson #13 / 20

Lesson 13: Constructors, Destructors (~), Initializer Lists & 'this' Pointer

NSNextSemโ€ขLast Updated: 5 Aug, 2026

๐Ÿ—๏ธ Object Lifecycle Management

Constructors initialize objects when created, while Destructors clean up resources (closing files, releasing Heap memory) when objects are destroyed.


๐Ÿ› ๏ธ Key Concepts

  • โš™๏ธ Parameterized Constructor: Initializes object fields at instantiation.
  • ๐Ÿš€ Member Initializer List (ClassName() : field1(val) {}): Fastest way to initialize class data members directly.
  • ๐Ÿงน Destructor (~ClassName()): Has no return type and takes no arguments. Executed when object goes out of scope.
  • ๐Ÿ‘ˆ this Pointer: Implicit pointer available inside member functions holding the address of the current object.

  • ๐Ÿ’ป Code Example: RAII Buffer Allocation Class

    โŠžC++ Source Code (main.cpp)
    #include <iostream>
    class DynamicBuffer {
    private:
    int *data;
    int size;
    public:
    // Constructor with Member Initializer List
    DynamicBuffer(int s) : size(s), data(new int[s]) {
    std::cout << "๐Ÿ—๏ธ Allocated buffer of size " << size << " on Heap." << std::endl;
    }
    // Destructor (RAII Resource Cleanup)
    ~DynamicBuffer() {
    delete[] data;
    std::cout << "๐Ÿงน Destructor freed Heap memory buffer." << std::endl;
    }
    };
    int main() {
    {
    DynamicBuffer buf(1024); // Object scope begins
    } // Object goes out of scope here -> Destructor fires automatically!
    return 0;
    }
    โŠžWindows 11 Pro Terminal Execution OutputWindows 11 Pro Verified
    โŠžAdministrator: Windows 11 Pro Command Prompt (g++ GCC 13.2.0)
    โ€”โ–กโœ•

    Microsoft Windows [Version 10.0.22631.3007] (Windows 11 Pro x86_64)

    (c) Microsoft Corporation. All rights reserved.

    C:\Users\Student\CPP_Project>#include <iostream>

    C:\Users\Student\CPP_Project> g++ -o main.exe main.cpp C:\Users\Student\CPP_Project> main.exe Hello World from C++ on Windows 11 Pro! [Process exited with code 0 in 0.001 seconds]

    Interactive Knowledge Check

    Test your understanding of Lesson #13 concepts

    When is a class Destructor (~ClassName()) automatically executed?