Search code examples
c++destructor

How do I call the class's destructor?


I have a simple C++ code, but I don't know how to use the destructor:

class date {

public:
    int day;
    date(int m)
    {
        day =m;
    }

    ~date(){
    cout << "I wish you have entered the year \n" << day;    
    }
};


int main()
{
  date ob2(12);
  ob2.~date();
  cout << ob2.day;
  return 0;
}

The question that I have is, what should I write in my destructor code, that after calling the destructor, it will delete the day variable?


Solution

  • You should not call your destructor explicitly.

    When you create your object on the stack (like you did) all you need is:

    int main()
    {
      date ob2(12);
      // ob2.day holds 12
      return 0; // ob2's destructor will get called here, after which it's memory is freed
    }
    

    When you create your object on the heap, you kinda need to delete your class before its destructor is called and memory is freed:

    int main()
    {
      date* ob2 = new date(12);
      // ob2->day holds 12
      delete ob2; // ob2's destructor will get called here, after which it's memory is freed
      return 0;   // ob2 is invalid at this point.
    }
    

    (Failing to call delete on this last example will result in memory loss.)

    Both ways have their advantages and disadvantages. The stack way is VERY fast with allocating the memory the object will occupy and you do not need to explicitly delete it, but the stack has limited space and you cannot move those objects around easily, fast and cleanly.

    The heap is the preferred way of doing it, but when it comes to performance it is slow to allocate and you have to deal with pointers. But you have much more flexibility with what you do with your object, it's way faster to work with pointers further and you have more control over the object's lifetime.