How do I manually remove an instance of a class?

advertisements

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;
}


Without knowing the use-case or the actual problem you want to solve (please read about the XY problem, your question is a good example of it) the simplest way is just reassigning:

Cheese swiss("Jarlsberg", 4.99);
...
swiss = Cheese("Gruyère",5.99);

That might of course require you to implement an assignment operator, but following the rules of three or five you should do that anyway (but the assignment operator is not needed if you follow the rule of zero).

You could also use pointers, if you explicitly want to destroy the current swiss object:

Cheese* swiss = new Cheese("Jarlsberg", 4.99);
...
delete swiss;
swiss = new Cheese("Gruyère",5.99);

But pointers is a can of worms that you should avoid, and don't really need much in modern C++. But pointers (or references) are needed if you want polymorphism. Then you could have a pointer to the base class pointing to the actual instance, and things like virtual functions will work as expected.

Also, and depending on your situation which we still know nothing about, you could of course use scoping:

Cheese swiss("Jarlsberg", 4.99);
...
{
    Cheese swiss("Gruyère",5.99);
    // In here the swiss cheese is a Gruyère
    ...
}
// Out here the swiss cheese is a Jarlsberg

Though shadowing variable names like this works, it's a bad habit that you should avoid as it adds confusion for readers of the code. On the other hand, even when using scopes nothing stops you from using any (valid) variable name you want, so you could name the outer scope instance jarlsberg and the inner scope instance gruyere, the gruyere object would then be destructed at the end of the scope just like any other nested-scope variable would be destructed and "disappear".