Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the difference between "int *a = new int" and "int *a = new int()"? [duplicate]

Tags:

c++

What is the difference between following two lines ?

int *a = new int;

int *a = new int();
like image 492
chom Avatar asked Oct 06 '13 21:10

chom


People also ask

What is new int () in C++?

The purpose of new is to simply reserve memory for storing an int variable on the heap instead of the traditional stack. The main advantage of using heap is that you can store a large number of int variables like in an array of 100000 elements easily on the heap.

What is difference between int * a and int &A?

There is a big difference between the two expressions. the value of the object a is converted to an integer value of the type int. the sub-expression (int*)&a says the compiler that there is allocated memory for an object of the type int that is that in the memory there is indeed stored a valid object of the type int.

What is the meaning of new int?

*new int means "allocate memory for an int , resulting in a pointer to that memory, then dereference the pointer, yielding the (uninitialized) int itself".

What is the difference between int and int * in C?

int means a variable whose datatype is integer. sizeof(int) returns the number of bytes used to store an integer. int* means a pointer to a variable whose datatype is integer. sizeof(int*) returns the number of bytes used to store a pointer.


2 Answers

int *a = new int;

a is pointing to default-initialized object (which is uninitialized object in this case i.e the value is indeterminate as per the Standard).

int *a = new int();

a is pointing to value-initialized object (which is zero-initialized object in this case i.e the value is zero as per the Standard).

like image 169
Nawaz Avatar answered Oct 16 '22 13:10

Nawaz


The first variant default-initializes the dynamically allocated int, which for built-in types such as int does not perform any initialization.

The second variant value-initializes it, which for int means zero-initialization, giving it value 0.

like image 23
juanchopanza Avatar answered Oct 16 '22 14:10

juanchopanza