Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it good practice to write constructor/destructor?

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:
};
like image 261
Zack Lee Avatar asked Aug 27 '18 01:08

Zack Lee


People also ask

Do we always need to define constructor and destructor for a class?

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.

What is the purpose of a constructor destructor?

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.

Is it correct to define destructor without defining constructor?

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 should a destructor be written?

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.


1 Answers

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.

like image 54
Ben Voigt Avatar answered Oct 21 '22 16:10

Ben Voigt