Menu
Destructors in C++

Destructors in C++

๐Ÿ“š C++ Destructors Notes: Comprehensive Guide

Playlist Link: C++ Series by The Cherno


๐Ÿ” Introduction to Destructors

Video Reference: Destructors in C++

  • Purpose: Destructors clean up resources when an object is destroyed (e.g., memory deallocation, closing files).
  • Called Automatically:
    • When stack-allocated objects go out of scope.
    • When delete is called on heap-allocated objects.

๐Ÿ—๏ธ Constructor vs. Destructor Syntax

Video Reference: Syntax Example

Example Code:

class Entity {
public:
    float x, y;

    // Constructor (Initialization)
    Entity() : x(0.0f), y(0.0f) {
        std::cout << "Created Entity!" << std::endl;
    }

    // Destructor (Cleanup)
    ~Entity() {
        std::cout << "Destroyed Entity!" << std::endl;
    }
};
  • Constructor: Runs when the object is created (e.g., Entity e;).
  • Destructor: Runs when the object is destroyed (e.g., end of scope or delete).

๐Ÿ—‚๏ธ Stack vs. Heap Allocation

Video Reference: Stack/Heap Behavior

Example 1: Stack Allocation

void Function() {
    Entity e; // Constructor called
    e.Print(); // Use the object
} // Destructor called automatically when scope ends

Output:

Created Entity!  
Destroyed Entity!  

Example 2: Heap Allocation

Entity* e = new Entity(); // Constructor called
delete e; // Destructor called manually

๐Ÿ’ก Use Cases for Destructors

Video Reference: Real-World Examples
Destructors are critical for:

  1. Freeing heap memory allocated in the constructor.
  2. Closing files/database connections opened by the object.
  3. Releasing other resources (e.g., GPU textures, network sockets).

Example: Preventing Memory Leaks

class Buffer {
private:
    int* data;
public:
    Buffer(int size) { data = new int[size]; }
    ~Buffer() { delete[] data; } // Cleanup in destructor
};

โš ๏ธ Manual Destructor Calls (Rare!)

Video Reference: Manual Destruction

  • Avoid unless necessary! Destructors are designed to be automatic.
    Entity e;
    e.~Entity(); // Manual call (risky, may cause double-free errors)
    

    Output:

    Destroyed Entity!  
    Destroyed Entity! // Crash risk if memory is freed twice
    

โœ… Key Takeaways

  1. Destructors ensure proper cleanup of resources.
  2. Stack objects auto-destroy at scope end; heap objects require delete.
  3. Never manually call destructors unless you fully understand the implications.

๐Ÿ“ผ Video Transcript & Main Link: Full Video
Use this guide to avoid rewatching the video! Revisit sections via timestamps if needed. ๐Ÿš€