How do I manually delete an instance of a class?

Viewed 45626

How do I manually delete an instance of a class?

Example:

#include <iostream>
#include <cstring>

class Cheese {
private:
    string brand;
    float cost;
public:
    Cheese(); // Default constructor
    Cheese(string brand, float cost); // Parametrized constructor
    Cheese(const Cheese & rhs); // Copy construtor
    ~Cheese(); // Destructor
    // etc... other useful stuff follows
}

int main() {
    Cheese cheddar("Cabot Clothbound", 8.99);
    Cheese swiss("Jarlsberg", 4.99);

    whack swiss; 
    // fairly certain that "whack" is not a keyword,
    // but I am trying to make a point. Trash this instance!

    Cheese swiss("Gruyère",5.99);
    // re-instantiate swiss

    cout << "\n\n";
    return 0;
}
6 Answers

A general Rule Locally created Instances are automatically deleted/taken care once it goes out of scope. Dynamically created Instances (Dynamic Memory Allocation) need to be deleted manually as follows:

delete instance_name;

  • Note : Do not include delete instance_name statement inside ~cheese() (~destructor), otherwise it will enter into a loop and crash

In above case where you manually want to delete the instance, it is recommended use DMA:

int main() {
    Cheese cheddar("Cabot Clothbound", 8.99);
    Cheese* swiss = new swiss("Jarlsberg", 4.99);

    delete swiss;


    Cheese swiss("Gruyère",5.99);
    // re-instantiate swiss

    cout << "\n\n";
    return 0;
}
Related