for example i want to define an integer . i can do it in two ways in C++:
int a = 10;
int a(10);
is there any difference between the two or it's just a matter of taste?
for example i want to define an integer . i can do it in two ways in C++:
int a = 10;
int a(10);
is there any difference between the two or it's just a matter of taste?
is there any difference between the two or it's just a matter of taste?
As long as you are dealing with fundamental data types such as int
, there is no difference. It is just a matter of preference, and I would personally opt for the first form - but that's just my taste. There may be a difference, though, when you are initializing class types.
The first form is called copy-initialization, and it conceptually works by first constructing a temporary object from the initializer (provided a suitable conversion sequence is available) and then copy-constructing (or move-constructing) the object being declared from that temporary.
Notice, that the compiler can perform copy elision per paragraph 12.8/31 of the C++11 Standard and practically optimize this form into direct-initialization (see the next paragraph). If this is done, however, a viable copy constructor or move constructor must still be present in order for the initialization to be valid.
The second form is called direct-initialization, and it works by constructing the object being declared directly, and passing the initializer expression as the argument to the constructor.
For basic types (int, float, double, long, char, etc), aside from the number of characters required to type the two options, the compiler should do exactly the same thing for both options. So from that perspective, it's just a matter of choice.
Obviously, style guides for the company you work for, or the open source project you are volunteering on, or the school you are being taught at, may say that one is preferred over the other.
There is no difference with primitive types.First type is called copy-initialization,while the second one direct-initialization.Take a look using google on how these 2 methods are different when you are initializing a class.