Differences between constructor syntax and assignment syntax for primitive type initialization

Reading the code written by a colleague, I came across the use of constructor syntax to initialize a variable of a primitive type. Those. something like below:

#include <iostream> int main() { using namespace std; // initialized using assignement syntax (copy initialisation) int titi = 20; cout << "titi=" << titi << "\n"; // got 20 in titi, it works // initialized using constructor syntax (direct initialization) int toto(10); cout << "toto=" << toto << "\n"; // got 10 in toto, it works } 

My natural tendency would be to stick with assignment syntax, as it is historical, and it has no problems, and there are obvious compatibility issues (constructor syntax will not qualify as valid C).

Still wondering if there is any other obvious difference between the two syntaxes? If they really mean the same thing? And what are the pros and cons of this or that form, taking into account, for example, problems of future maintenance / code development or problems with readability?

+4
source share
2 answers

For simple types, such as int , there is no difference. For class types, what you call the "constructor syntax" is known as direct initialization and what you call the assignment syntax, like copying. You can not use copy initialization, if the class supports copy, so the tendency is to initialize (with the proviso that then have to worry about is the most troublesome problem parsing). Some people then advocate direct initialization syntax everywhere, based on homogeneity: use the same format everywhere.

+3
source

The constructor syntax is useful when working with templates, because you do not know if the type will be a primitive type or class.

+2
source

Source: https://habr.com/ru/post/1491814/


All Articles