Extra 5% OFF Use Code: OL05
Free Shipping over ₹999

Destructor

What is Destructor ?

In Object-Oriented Programming (OOP), a destructor is a special member function of a class that is automatically invoked when an object of the class is destroyed. The primary purpose of a destructor is to free up resources that the object may have acquired during its lifetime, such as memory, file handles, or network connections.

Key Points about Destructors:

  1. Automatic Invocation:
    • A destructor is called automatically when an object goes out of scope or is explicitly deleted.
  2. Name:
    • The destructor has the same name as the class but is preceded by a tilde (~). For example, if the class name is Student, the destructor will be ~Student().
  3. No Return Type:
    • Destructors do not have a return type, not even void.
  4. No Parameters:
    • Destructors do not take any parameters, and hence, they cannot be overloaded.
  5. Single Destructor per Class:
    • There is only one destructor per class.
  6. Memory Management:
    • Destructors are crucial for managing dynamic memory in languages like C++ to avoid memory leaks.

Example of Destructor: VideoGame Class

Imagine you are developing a simple video game where the player can start a game session and then end it. When the game session ends, you want to make sure that all resources used by the game are properly released—such as saving the player’s progress and closing any open files. This is where a destructor comes into play.

Code

#include <iostream>
#include <fstream>
using namespace std;

class VideoGame {
private:
    string playerName;
    fstream saveFile;

public:
    // Constructor: Initialize game session and open save file
    VideoGame(string name) {
        playerName = name;
        saveFile.open("savefile.txt", ios::out);
        if (saveFile.is_open()) {
            cout << "Game session started for " << playerName << "." << endl;
            saveFile << "Player: " << playerName << endl;
        } else {
            cout << "Failed to open save file." << endl;
        }
    }

    // Method to simulate playing the game
    void play() {
        cout << playerName << " is playing the game..." << endl;
        saveFile << "Playing game...\n";
    }

    // Destructor: Save progress and close the save file
    ~VideoGame() {
        if (saveFile.is_open()) {
            saveFile << "Game session ended." << endl;
            saveFile.close();
            cout << "Game session for " << playerName << " has ended and progress has been saved." << endl;
        }
    }
};

int main() {
    {
        // Create an object of VideoGame
        VideoGame game("Alice");
        game.play();
    } // Destructor is automatically called here when 'game' goes out of scope

    return 0;
}

Output:

Game session started for Alice.
Alice is playing the game...
Game session for Alice has ended and progress has been saved.

Explanation:

Step 1 : Constructor: Starting the Game Session

VideoGame(string name) {
    playerName = name;
    saveFile.open("savefile.txt", ios::out);
    if (saveFile.is_open()) {
        cout << "Game session started for " << playerName << "." << endl;
        saveFile << "Player: " << playerName << endl;
    } else {
        cout << "Failed to open save file." << endl;
    }
}

Purpose:

  • The constructor initializes the game session by setting the player’s name and opening a file (savefile.txt) where the player’s progress will be save.

Actions:

  • If the file is successfully opened, it logs that the game session has started and writes the player’s name to the file.

Example Usage:

  • When the VideoGame object is created (e.g., VideoGame game("Alice");), this constructor runs, indicating that Alice’s game session has started.

Step 2: Playing the Game

void play() {
    cout << playerName << " is playing the game..." << endl;
    saveFile << "Playing game...\n";
}

Purpose:

  • This method simulates the player playing the game by writing a message to the console and logging the activity in the save file.

Example Usage:

  • When game.play(); is called, it simulates the player playing the game.

Step 3: Destructor: Ending the Game Session

~VideoGame() {
    if (saveFile.is_open()) {
        saveFile << "Game session ended." << endl;
        saveFile.close();
        cout << "Game session for " << playerName << " has ended and progress has been saved." << endl;
    }
}

Purpose:

  • The destructor ensures that when the VideoGame object is destroyed (goes out of scope), the game session is properly ended, progress is logged, and the save file is closed.

Actions:

  • It checks if the save file is still open, writes that the game session has ended, closes the file, and displays a message confirming that the player’s progress has been saved.

Example Usage:

  • The destructor is automatically invoked when the game object goes out of scope, ensuring that resources are properly released.

Step 4 : Main Function: Using the VideoGame Class

int main() {
    {
        // Create an object of VideoGame
        VideoGame game("Alice");
        game.play();
    } // Destructor is automatically called here when 'game' goes out of scope

    return 0;
}
  • Scope and Destructor Call:
    • The VideoGame object game is created within a block. Once the block is exited, the destructor is automatically called, ensuring that Alice’s game session ends properly and her progress is saved.

Summary:

  • Destructor in Action:
    • The VideoGame class uses a destructor to ensure that when a game session ends, all necessary cleanup is done, such as saving progress and closing files.
  • Real-Life Analogy:
    • Just like in a real game where you want to save your progress before quitting, the destructor in the VideoGame class ensures that everything is properly saved and cleaned up when the game object is destroyed.

    Leave a Reply

    Your email address will not be published.

    Need Help?