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; }
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.
An int variable contains only whole numbers Int, short for "integer," is a fundamental variable type built into the compiler and used to define numeric variables holding whole numbers. Other data types include float and double. C, C++, C# and many other programming languages recognize int as a data type.
What Does Integer (INT) Mean? An integer, in the context of computer programming, is a data type used to represent real numbers that do not have fractional values. Different types of integer data types are stored on machines in different ways.
int* means a pointer to a variable whose datatype is integer. sizeof(int*) returns the number of bytes used to store a pointer. Since the sizeof operator returns the size of the datatype or the parameter we pass to it.
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()
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