Destructors

A destructor is another special class method, complimentary to a constructor, that cleans up resources by deleting the contents in the storage used for an object when it goes out of scope, or when the delete keyword is used on an object.

 

Has the same name as the class, preceded by a tilde ~

Has no return data type.

Takes no arguments.

 

Cannot be explicitly called. It is automatically called when the object goes out of scope.

 

If no destructor is defined, the compiler will automatically provide one for you. However, there might be time when you want to ensure the object has been cleaned, or you might want to carry out a quick exit task such as leaving a message.

 

Compile & Run:

Hello, World!
myVar = 42
See ya later...

Leave a Reply