c++default-constructorvariable-initialization

Difference between int i(x); and int i = x;


I have been practicing C++ in HackerRank. There I was seeing different submissions and something new came in my sight. someone used int i(0) in for loop like

for (int i(0), mark; i<q; ++i)

So my question is :

  1. what is Difference between int i(x); and int i = x;? (where x is type of int defined in initialized before these lines).

Solution

  • The answer is essentially here.

    int i(x); is direct initialization which

    Initializes an object from explicit set of constructor arguments.

    whereas int i = x; is copy initialization, which

    Initializes an object from another object

    (The following is probably irrelevant for int, so take it as comment about the difference of the two syntaxes for actual classes: A i(x); vs A i = x;.)

    Notice, that both syntaxes can result in a copy constructor being called: if a copy constructor exists for the class A, then the explicit set of constructor arguments that you can provide via direct initialization can consist of exactly one object of class A (which is by the way exactly what happens if x is an int/A in int i(x);/A i(x);.

    This is to say that copy initialization is not the only way to construct an object copying it from another object of the same class.

    Another point worth noting, in my opinion, is that copy initialization doesn't necessarily mean that copy constructor will be called. If the class A has (beside the copy constructor A(A const&), if you like) the constructor A(int), that is the constructor that will be called if you write A a = 3;.

    All this is to say that in my opinion the names of the 6 syntaxes you find listed at the first link I provided are not really telling you what happens; the same thing can happen for more syntaxes, and different things can happen for the same syntax. Those 6 are just names to refer to the syntax of the initialization, not to how the process of initialization happens, because the latter depends on the class of the initialized object and on the initializer object (and on the syntax you pick, sure).