Dr Negative Dr Negative - 1 year ago 107
C++ Question

Meaning of intrinsic type with () in C++

What does it mean when an intrinsic type has the parenthesis operators with it.

e.g. int() or float()

Is it like a default constructor or does it have a different meaning for intrinsic types?


To add more context:

In my school textbook for C++, I am on a chapter about Templates. A template being used for demonstration is a Table template (a 2D array). One of the functions for Table is a resize method to change the dimensions of the table and is also used in some constructors used for Table. The constructor in question and the resize method are:

template <typename T>
Table<T>::Table<T>(int m, int n)
mDataMatrix = 0;
mNumRows = 0;
mNumCols = 0;
resize(m, n, T());


template <typename T>
void Table<T>::resize(int m, int n, const T& value)
// Destroy the previous data.

// Save dimensions.
mNumRows = m;
mNumCols = n;

// Allocate a row (array) of pointers.
mDataMatrix = new T*[mNumRows];

// Now, loop through each pointer in this row array.
for(int i = 0; i < mNumRows; ++i)
// And allocate a column (array) to build the table.
mDataMatrix[i] = new T[mNumCols];

// Now loop through each element in this row[i]
// and copy 'value' into it.
for(int j = 0; j < mNumCols; ++j)
mDataMatrix[i][j] = value;

In the constructor definition, resize's third argument is T() (and I assume T becomes whatever the specified type for the template is).

In the definition for resize, T() is used for the value argument to assign a default value to the elements in the table.

From some of the earlier answers, this is zero-initialization. I assume that means the value is 0 for each element in the table (or some equivalent of 0 if the type is a string, I guess). Is this correct?

Answer Source

That is value initialization.

e.g. auto x = int(); means int x = 0

In the example provided T() will create an object of type T and pass it as a parameter.

You could also write:

resize(m, n, T{}); 
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download