How do I call the class’s destructor?

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.

Leave a Comment