Starting out in c++ and noticed that you could initialise a variable in two ways
int example_var = 3; // with the assignment operator '='
or
int example_var(3); // enclosing the value with parentheses
is there a reason to use one over the other?
The first form dates back from the C time, while the second was added in C++. The reason for the addition is that in some contexts (in particular initializer lists in constructors) the first form is not allowed.
The two are not exactly equivalent for all types, and that is where one or the other might be more useful. The first form semantically implies the creation of a temporary from the right hand side, followed by the copy construction of the variable from that temporary. The second form, is direct initialization of the variable from the argument.
When does it matter?
The first form will fail if there is no implicit conversion from the right hand side to the type of the variable, or if the copy constructor is not available, so in those cases you will have to use direct initialization.
The second form can be used in more contexts than the first, but it is prone to the most-vexing-parse. That is, in some cases the syntax will become compatible with a declaration for a function (rather than the definition of a regular variable), and the language determines that when this is the case, the expression is to be parsed as a function declaration:
std::string s = std::string(); // ok declares a variable
std::string s( std::string() ); // declares a function: std::string s( std::string(*)() )
Finally in C++11 there is a third form, that uses curly braces:
std::string s{std::string{}};
This form has the advantages of direct initialization with parenthesis, but at the same time it is not prone to misinterpretation.
Which one to use?
I would recommend the third option if available. That being said, I tend to use the first more often than not, or the second depending on the context and the types...
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