27

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;
}
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
coinsyx
  • 643
  • 2
  • 7
  • 13
  • See also: I had asked a similar question (months before seeing this question) that now has some other great answers here too: [What is a call to `char()`, `uint8_t()`, `int64_t()`, integer `T()`, etc, as a function in C++?](https://stackoverflow.com/q/72367123/4561887) – Gabriel Staples Sep 05 '22 at 21:46

3 Answers3

33

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()
juanchopanza
  • 223,364
  • 34
  • 402
  • 480
-1

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.

-2

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.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Rabbiya Shahid
  • 422
  • 3
  • 14