destructors

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • femina
    New Member
    • Dec 2007
    • 35

    destructors

    when can i call a destructor explicitily
    delete is one way
    but can i be able to call ~classname() explicitly please give me any scenario where we need to call destructor explicitly
  • jthep
    New Member
    • Oct 2007
    • 34

    #2
    I'm not sure but I think one reason to call the destructor is when you have members of the object specifically a pointer that points to objects stored somewhere other than the stack which immediately gets taken care of when you leave the function.

    Say you declare a linked list which has a member head that is a pointer to the first node. The node is stored on the heap, if you call delete it will delete the pointer, but it'll leave the node on the heap. Thats when you need a destructor to go in and delete the nodes that is stored on the heap.

    Comment

    • weaknessforcats
      Recognized Expert Expert
      • Mar 2007
      • 9214

      #3
      A destructor is just a regular function that has no magic powers. When an object is to be destroyed, the compiler will call your destructor so you can clean up any memory allocations, and such, before the object goes bye-bye.

      That means you can call the destructor yourself anytine you need to clean up the this object. On example is overloading the assignment operator. In this case, the this object need to have its contents removed before they are overstored by the contents of the assigned from object. Like this:

      [code=cpp]
      Class Class::operator =(const Class& rhs)
      {
      if (this == &rhs) return *this; //no self-assignment
      Class::~Class() ; //OK to assign, delete current contents
      this->data = ths.data; //replace contents with rhs data
      return *this;
      }
      [/code]

      Comment

      Working...