Question:

When Destructor is called in C++?

by  |  earlier

0 LIKES UnLike

when destructor is called.Is it when delete is used?

 Tags:

   Report

3 ANSWERS


  1. In C++ you call the destructor yourself when you no longer need the class, just like any other function. Like a constructor, however; you do not need to have a destructor. If your class has no resources to clean-up after there is no need for a destructor. Poor use of destructors (and other means of clean-up) were a powerful motivation for the garbage collection system used by most other languages.

    A destructor in C++ has the same name as the class (like the constructor) but is preceeded by the "~" (tilde) character. So, for the class A, you would have:

    A::~A( ) {  //do some cleanup }

    Typically, you call the destructor by using the anti-new keyword, delete.


  2. It deconstructs the collected structure. You're looking for Garbage Collection if you want to delete useless used data. It can free up memory and eliminate memory leaks.

  3. Yes, the destructor is called when delete is used; it is also called when a local object goes out of scope. To clarify the latter:

    class myClass

    {

         myClass(){}

         ~myClass(){}

    };

    Then, we may say,

    void myFunction()

    {

         myClass X();

         //do something

    }

    int main()

    {

         myFunction();

         return 0;

    }

    and the destructor will be called at the end of myFunction, when the object X goes out of scope.

    There is often no need to call the destructor directly. If your constructor dynamically allocates memory, for example, and you call your destructor (which de-allocates that memory), and then it is automatically called by the delete operator later, then an error will occur.

Question Stats

Latest activity: earlier.
This question has 3 answers.

BECOME A GUIDE

Share your knowledge and help people by answering questions.
Unanswered Questions