Day 46: Constructors & Destructors OOPs (Part 3)

๐Ÿ“… Date: Feb 15, 2026

๐Ÿง  Mood: God Mode (Creating Life) ⚡

๐Ÿ”ฅ Topic: OOPs Part 3: Constructors & Destructors

๐Ÿ‘ถ The Life Cycle of an Object

Just like humans, Objects in C++ have a life cycle:

  • Birth: When memory is allocated (Constructor).
  • Life: When we use the object (calling functions).
  • Death: When memory is cleared (Destructor).

๐Ÿ› ️ 1. Constructor (The Setup Wizard)

Imagine buying a new phone. When you switch it on for the first time, it asks for "Language, Wifi, Google Account". That is initialization.

A Constructor is a special function that runs automatically when an object is created.

๐Ÿ“œ The 3 Rules

  1. It has the Same Name as the Class.
  2. It has NO Return Type (not even void).
  3. It must be Public (usually).

๐Ÿ’ป Code Example: Default vs Parameterized

#include <iostream>
using namespace std;

class Hero {
    public:
    int health;

    // 1. Default Constructor (No arguments)
    Hero() {
        cout << "Constructor Called: Hero Created!" << endl;
        health = 100; // Default Value set automatically
    }

    // 2. Parameterized Constructor (With inputs)
    Hero(int h) {
        cout << "Parameterized Constructor Called!" << endl;
        health = h;
    }
};

int main() {
    // Calls Default Constructor
    Hero h1; 
    cout << "H1 Health: " << h1.health << endl;

    // Calls Parameterized Constructor
    Hero h2(500); 
    cout << "H2 Health: " << h2.health << endl;

    return 0;
}

๐Ÿ’€ 2. Destructor (The Grim Reaper)

When an object's work is done (e.g., when the function ends), C++ automatically deletes it to free up memory. The Destructor is the last function called before death.

๐Ÿ“œ Syntax Rule

It has the same name as the class but with a Tilde (~) sign before it. Example: ~Hero()

๐Ÿ’ป Code: Birth & Death

class Player {
    public:
    // Constructor (Birth)
    Player() {
        cout << "✅ Player Logged In (Memory Allocated)" << endl;
    }

    // Destructor (Death)
    ~Player() {
        cout << "❌ Player Logged Out (Memory Freed)" << endl;
    }
};

int main() {
    cout << "--- Game Start ---" << endl;
    
    Player p1; // Constructor runs here

    cout << "--- Game End ---" << endl;
    return 0; 
    // Destructor runs here AUTOMATICALLY
}

Note: You will see the Destructor message AFTER "Game End" is printed.


๐Ÿš€ Day 46 Challenge

Create a class Laptop.

  1. Use a Constructor to set the default battery = 100.
  2. Create a function use() that decreases battery.
  3. Use a Destructor to print "Shutting Down..." when the program ends.

Next Up: Day 47 - The "Copy" Constructor & Shallow vs Deep Copy.

No comments:

Post a Comment