Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I call the class's destructor?

Tags:

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?

like image 997
user261002 Avatar asked Oct 27 '10 18:10

user261002


People also ask

Can a class function call destructor?

Technically yes, but be careful, you should not use the deleted object, this and non-static members anymore: delete this; You can also call the destructor: ~Thread();

Is base class destructor called automatically?

No, destructors are called automatically in the reverse order of construction. (Base classes last). Do not call base class destructors.


2 Answers

Rarely do you ever need to call the destructor explicitly. Instead, the destructor is called when an object is destroyed.

For an object like ob2 that is a local variable, it is destroyed when it goes out of scope:

int main()  {      date ob2(12);   } // ob2.~date() is called here, automatically! 

If you dynamically allocate an object using new, its destructor is called when the object is destroyed using delete. If you have a static object, its destructor is called when the program terminates (if the program terminates normally).

Unless you create something dynamically using new, you don't need to do anything explicit to clean it up (so, for example, when ob2 is destroyed, all of its member variables, including day, are destroyed). If you create something dynamically, you need to ensure it gets destroyed when you are done with it; the best practice is to use what is called a "smart pointer" to ensure this cleanup is handled automatically.

like image 175
James McNellis Avatar answered Sep 28 '22 11:09

James McNellis


You do not need to call the destructor explicitly. This is done automatically at the end of the scope of the object ob2, i.e. at the end of the main function.

Furthermore, since the object has automatic storage, its storage doesn’t have to be deleted. This, too, is done automatically at the end of the function.

Calling destructors manually is almost never needed (only in low-level library code) and deleting memory manually is only needed (and only a valid operation) when the memory was previously acquired using new (when you’re working with pointers).

Since manual memory management is prone to leaks, modern C++ code tries not to use new and delete explicitly at all. When it’s really necessary to use new, then a so-called “smart pointer” is used instead of a regular pointer.

like image 38
Konrad Rudolph Avatar answered Sep 28 '22 11:09

Konrad Rudolph