Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Should i define the default constructor? [closed]

So we were doing some peer review, and this minor disagreement rose up,

Should the default constructor be defined even if it does nothing, or should we let the compiler define it?

So far, none of the sides could come up with any major advantages or disadvantages. What are the pros and cons of each style and which one is considered "cleaner"?

like image 369
user1708860 Avatar asked Mar 04 '14 22:03

user1708860


1 Answers

This is likely to be closed as "primarily opinion-based," but I can give you some objective points to consider:

  • If you don't define the default constructor, and someone later adds a constructor with parameters and forgets to also add the parameterless constructor, the default constructor will go away and that could break existing code. Explicitly defining it ensures that even if someone adds an overloaded constructor later, the parameterless one is still there.

  • If the constructor is declared in the header and defined out-of-line (in a .cc/.cpp file), then the implementation can later be modified with dependent code only needing to be re-linked. Declaring a constructor after the fact necessarily affects the header, requiring recompilation of dependent code.

    • An empty out-of-line constructor will still need to be called, incurring a small run-time cost, whereas with an implicitly provided default constructor the compiler can see that nothing needs to be done and avoid the call.

  • Defining it explicitly requires more typing and results in more lines of code. There is a small but nonzero cost associated with this (time taken to type it in, and time taken for readers of the code to read through it).

  • Defining it explicitly disqualifies the class from being an aggregate class, unless you use =default in C++11.

Yes, these points are contradictory. I think you will find that the prevailing opinion is not to define it explicitly, but as far as the language is concerned there is no correct or incorrect way. (Unless you need your type to be an aggregate.)

like image 128
TypeIA Avatar answered Sep 19 '22 15:09

TypeIA