'What does int() do in C++?
The following code can pass compiling and will print 0 on the console. I saw similar code in STL. Does type int in C++ have a constructor? Is int() a call of some defined function?
int main()
{
int a = int();
cout << a << endl;
return 0;
}
Solution 1:[1]
In this context,
int a = int(); // 1)
it value-initializes a, so that it holds value 0. This syntax does not require the presence of a constructor for built-in types such as int.
Note that this form is necessary because the following is parsed as a function declaration, rather than an initialization:
int a(); // 2) function a() returns an int
In C++11 you can achieve value initialization with a more intuitive syntax:
int a{}; // 3)
Edit in this particular case, there is little benefit from using 1) or 3) over
int a = 0;
but consider
template <typename T>
void reset(T& in) { in = T(); }
then
int i = 42;
reset(i); // i = int()
Solution 2:[2]
first, we start with this syntax:
type variableName = type();
this syntax is called value initialization of a variableName, or in other word we say a variableName is zero initialized.
But, what is the meaning of the value initialization.
if the type of a variableName is a built-in/scalar type like (int, char, ...), value initialization mean that a variableName is initialized with the value zero.
and if the type is a complex type like (classes, structs, ...) mean that a variableName is initialized by calling its default constructor.
Solution 3:[3]
int() is the constructor of class int. It will initialise your variable a to the default value of an integer, i.e. 0.
Even if you don't call the constructor explicitly, the default constructor, i.e. int() , is implicitly called to initialise the variable.
Otherwise there will be a garbage value in the variable.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | |
| Solution 2 | |
| Solution 3 | Peter Mortensen |
