What does int() do in C++?

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()

Leave a Comment