What is the difference between following two lines ?
int *a = new int;
int *a = new int();
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.
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.
*new int means "allocate memory for an int , resulting in a pointer to that memory, then dereference the pointer, yielding the (uninitialized) int itself".
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.
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).
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
.
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