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!
I read though that
intis 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.
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With