I'm having a hard time understanding the application of destructors to a class. My book only gives one example and it's not the best and the examples online I couldn't get the grasp of.
I created this class and I need to add a destructor to it but I'm unsure of how to do it. I attempted it at the bottom but I get an error of cannot delete expression type 'double'.
delete is only used to destroy things that has been created with new. There is nothing that needs to be done in the destructor for this class. radius and pi will be automatically destroyed when the Circle object is destroyed.
- Destructors allow the user of a class to not have to worry about any resources used in the implementation of said class.
- Destructors are only useful for freeing resources that wouldn't automatically be freed just by the object going out of scope. For example, an std::fstream's destructor calls close(), freeing the file back to the operating system. An std::vector's destructor will delete its internal array of memory. The user can treat it like any other stack-allocated object; I don't need to care about exactly what resources are at play under the hood in the std::vector class.
- Destructors are called even when an exception occurs halfway through the function, allowing for exception-safe resource deallocation.
In your example, you only have simple, stack-allocated objects in your class (radius and pi), so nothing needs to happen in your destructor.