I'm currently trying to learn about classes and constructors/destructors. I understand what the two do, but I'm having a harder time with the destructors because I can't think of a practical application for its use.
Can anyone provide an example with an explanation?
Destructors are special member functions used to release any resources allocated by the object.
The most common example is when the constructor of the class uses new
, and the destructor uses delete
to deallocate the memory.
class Myclass
{
int *m_ptr;
public:
Myclass():m_ptr(new int)
{
}
~Myclass()
{
delete m_ptr;
}
//ToDo: Follow Rule of Three
//Provide definitions for copy constructor & copy assignment operator as well
};
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