Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Practical application of class destructor

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?

like image 821
Painguy Avatar asked Nov 30 '22 02:11

Painguy


1 Answers

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

};
like image 100
Alok Save Avatar answered Dec 04 '22 14:12

Alok Save