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.