Destructors

Jul 23, 2018 at 8:06pm
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'.

Thanks in advance.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
#ifndef CIRCLE_H
#define CIRCLE_H

class Circle
{
    private:
        double radius;
        double pi;
    public:
        Circle() 
            {
                radius = 0.0;
                pi = 3.14159;
            }
        Circle(double r)  
            {
                radius = r;
                pi = 3.14159;
             }
        void setRaidus(double r)
            {radius = r;}
        double getRadius() const 
            {return radius;}
        double getArea() const  
            {return (pi * radius * radius);}
        double getDiameter() const
            {return (radius * 2);}
        double getCircumference() const
            {return (2 * pi * radius);}


        ~Circle() //Here was my failed attempt at a destructor
            {
                delete radius;
                delete pi;
            }
};      

#endif 
Last edited on Jul 23, 2018 at 8:08pm
Jul 23, 2018 at 8:15pm
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.
Last edited on Jul 23, 2018 at 8:16pm
Jul 23, 2018 at 8:24pm
It's all about RAII.
https://en.wikipedia.org/wiki/Resource_acquisition_is_initialization
* Resource allocation is done during object creation (specifically initialization), by the constructor.
* Resource deallocation is done during object destruction.

- 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.

Jul 23, 2018 at 8:26pm
Ahhhh ok thank you both for the responses that definitely clears it up!
Topic archived. No new replies allowed.