Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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!

like image 698
Tomasito665 Avatar asked Nov 25 '25 16:11

Tomasito665


2 Answers

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.

like image 191
legends2k Avatar answered Nov 27 '25 04:11

legends2k


C++ and java work differently when it comes to types. While java (to my understanding) uses basic built in types and reference types, C++ uses a different type system.

C++ built in types includes fundamental types (bool, character types like char, integer types, floating point types, and void) as well as some other types such as reference types like double& or std::vector<std::sting>&& and pointer types.

In addition to those, C++ supports user defined types (structs, classes, enum and enum class). the standard library provides many user defined types such as std::string.

it turns out the int a(5); notation is NOT reserved for user defined types only, The ,language supports value initialization that way. in C++11 it is also legal to say int a{5};

now about value assignment:

int a; //declaration
a=5;   //assignment

int b(5); //declaration+initialization
int c=5;  //declaration+initialization (NO assignment)

If a variable has not been declared, there is no assignment, the compiler parses int c=5; just like int c(5);

like image 37
ForeverStudent Avatar answered Nov 27 '25 04:11

ForeverStudent



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!