I wonder if it's a good practice to always write constructor/destructor even if I don't use them.
class Foo
{
public:
Foo(){};
~Foo(){};
};
Or is it a better practice to write them only when I actually use them?
class Foo
{
public:
};
If you are okay with the default behavior that you get without a constructor, then there's no need to write a constructor; OTOH if you need to specify on-construction behavior explicitly, writing a constructor is the way to do that.
Constructor is used to initialize an object of the class and assign values to data members corresponding to the class. While destructor is used to deallocate the memory of an object of a class. There can be multiple constructors for the same class. In a class, there is always a single destructor.
Yes, the destructor is nothing more than a function. You can call it at any time. However, calling it without a matching constructor is a bad idea.
When a class contains a pointer to memory allocated in class, we should write a destructor to release memory before the class instance is destroyed.
It's a bad idea to user-define special member functions when the default ones are sufficient.
You will lose the default-generated move operations, see Does a default virtual destructor prevent compiler-generated move operations?
Your class will no longer be trivial, causing allocation and deallocation and containers holding your class to become much less efficient.
The defaulted definitions may be automatically noexcept
, but you lost that.
Your class is no longer an aggregate, so you can't use aggregate initialization.
If you make the destructor virtual, as shown in your question, you also lose standard-layout.
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