๐ 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
- It has the Same Name as the Class.
- It has NO Return Type (not even void).
- 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.
- Use a Constructor to set the default
battery = 100. - Create a function
use()that decreases battery. - 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