When you create an object, you usually want to give it some starting values (like setting a player's health to 100). When an object is deleted, you might need to clean up memory. C++ handles this automatically using Constructors and Destructors.
1. The Constructor
What it is: A special member function that is called automatically when an object is created.
Rules: It must have the exact same name as the Class and it does not have a return type (not even
void).Purpose: To initialize the object's attributes.
2. The Destructor
What it is: A special function called automatically when an object goes out of scope or is deleted.
Rules: Same name as the class but prefixed with a tilde (
~). It takes no parameters.Purpose: To release memory or close files (clean up).
Code Example: Life Cycle of a Game Character
Notice how we don't manually call the Character() function; it happens the moment we declare the variable.
#include <iostream>
#include <string>
using namespace std;
class GameCharacter {
public:
string name;
int health;
// 1. CONSTRUCTOR
// Runs when: GameCharacter p1("Aragorn"); is called
GameCharacter(string n) {
name = n;
health = 100;
cout << "[System]: " << name << " has entered the world." << endl;
}
// 2. DESTRUCTOR
// Runs when the program ends or the object is destroyed
~GameCharacter() {
cout << "[System]: " << name << " has left the world (Object destroyed)." << endl;
}
void status() {
cout << name << " Health: " << health << endl;
}
};
int main() {
cout << "--- Game Start ---" << endl;
// Creating objects (This triggers the Constructor)
GameCharacter p1("Warrior");
p1.status();
{
// A temporary character in a smaller scope
GameCharacter p2("Ghost");
p2.status();
} // p2 goes out of scope here (This triggers p2's Destructor)
cout << "--- Game Ending ---" << endl;
return 0;
} // p1's Destructor triggers hereKey Concept: Overloading Constructors
You can have multiple constructors for one class! For example, one that takes no names (default) and one that takes a name and a level. This gives you flexibility in how you "build" your objects.