4

Should destructior be declared/implemented in pointerless class? Is there any advantage of having/not having it ?

What I men is:

class Point
{
public: 
    int X, Y;
    Point(int x, int y);
    //~Point(void);       //should I uncoment it and implement empty destructor ?
}
EOG
  • 1,677
  • 2
  • 22
  • 36

2 Answers2

5

Should destructior be declared/implemented in pointerless class?

No need[conditions apply]. the compiler will generate one for you.
You should provide one only if you want to perform something specific, which the compiler will not.
For example:

  • Resource management(Memory managemnt, FIle handling),
  • Logging,
  • Close network connections,
  • In short custom functionality which needs to execute each time a object is destroyed

In general the thumb rule is:
"If you need to provide a copy constructor or a copy assignment operator then you most probably also need to provide your own destructor."
Popularly, this rule is known as the Rule of Three.


[conditions apply] If your class is meant to act as an Base class for Inheritance and your implementation will require calling delete on a Base class pointer pointing to a derived class object then you need to provide a destructor and mark it as virtual in Base class, failure to do so will result in Undefined Behavior.


Is there any advantage of having/not having it?

None, since the compiler does the same there is no need to do the extra typing.

Community
  • 1
  • 1
Alok Save
  • 202,538
  • 53
  • 430
  • 533
2

No, you shouldn't have a non-virtual destructor if you're not managing resources.

If you expect to derive from the class and plan on polymorphic deletion (i.e. delete a derived object through a base class pointer), you need a virtual destructor.

In fact, you shouldn't be managing resources directly, but have wrappers - i.e. smart pointers instead of raw pointers & manual allocation/deallocation.

Luchian Grigore
  • 253,575
  • 64
  • 457
  • 625