Search code examples
c++constructorinitializationprimitive

Why is int x = int(5) legal if int is not a class?


From what I understand it is legal to instantiate an integer in c++ like this:

int x = int(5);

As a Java programmer I would assume that this line of code calls the constructor of the integer passing "5" as an argument. I read though that int is not a class and thus has no constructor.

So, what does exactly happen in that line of code and what is the fundamental difference between initialising the int that way and this way:

int x = 5;

Thanks in advance!


Solution

  • I read though that int is not a class and thus has no constructor.

    Yes, technically built-in types have no constructor.

    what does exactly happen in that line of code

    The integer literal 5 is explicitly cast to an int (a no-op for the compiler mostly) and assigned to x.

    what is the fundamental difference between initialising the int that way and int x = 5;

    Essentially, no difference. All the below expressions are the same in most cases, unless you're a language lawyer (for instance, the last would prevent narrowing i.e. raise an error if the value cannot be represented by the type):

    int x = 5;         // copy initialization
    int y = int(5);    // cast and copy initialization
    int z = (int)5;    // cast and copy initialization
    int w(5);          // direct initialization
    int r{5};          // direct initialization
    

    Read more about initializations for finer details and differences.