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?
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();
No, destructors are called automatically in the reverse order of construction. (Base classes last). Do not call base class destructors.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With