Yahoo Answers is shutting down on May 4th, 2021 (Eastern Time) and the Yahoo Answers website is now in read-only mode. There will be no changes to other Yahoo properties or services, or your Yahoo account. You can find more information about the Yahoo Answers shutdown and how to download your data on this help page.

How to use a destructor in C++?

My book seems to be pretty terse on how to use destructors, and I haven't been able to make it work. I know when you want to call a destructor you need a tilde character and then the class name followed by parentheses. Do you also need to include the destructor as a prototype in the class interface? Do you need to define it in the implementation?

2 Answers

Relevance
  • cja
    Lv 7
    8 years ago
    Favorite Answer

    You say: "I know when you want to call a destructor ...". No, you don't call a destructor. In the class specification, the destructor will look like this:

    ~MyClass( );

    and you define it this way:

    MyClass::~MyClass( ) {

        // delete allocated memory, etc.

    }

    And you'd only need to define a destructor if it has something to do. If memory is allocated in your constructor, for example, or by any other operation in the class, you need to clean that up (free the memory) in the destructor.

    If you've dynamically allocated an instance of this class:

        MyClass *obj = new MyClass;

    The destructor is called when you do this:

        delete obj;

    If you've declared an instance of this class:

        MyClass obj;

    The destructor is called when obj goes out of scope, e.g. at the end of the function in which it's declared.

  • 8 years ago

    You don't use or call destructors; they are called implicitly when an object is deleted. You can define a destructor for an object that will be used to destroy it, if the standard destructor is not satisfactory.

Still have questions? Get your answers by asking now.