I have seen the related answers here and here on this, but I wanted confirmation, because none of them make this explicit.
Suppose I have a class Foo
and a member bar
of type int*
.
Are the following two initializations entirely equivalent?
Foo::Foo() : bar(NULL) // null pointer constant by macro
{
}
Foo::Foo() : bar() // value initialization
{
}
In computer programming, initialization (or initialisation) is the assignment of an initial value for a data object or variable. The manner in which initialization is performed depends on the programming language, as well as the type, storage class, etc., of an object to be initialized.
You are definitely encouraged to set pointers to NULL whenever the alternative is your pointer having an indeterminate value. Usage of pointers with an indeterminate value is undefined behavior, a concept that you might not grasp properly if you're used to C programming and come from higher level languages.
All pointers, when they are created, should be initialized to some value, even if it is only zero. A pointer whose value is zero is called a null pointer. Practice safe programming: Initialize your pointers!
Pointer arithmetic and arrays. Add an integer to a pointer or subtract an integer from a pointer. The effect of p+n where p is a pointer and n is an integer is to compute the address equal to p plus n times the size of whatever p points to (this is why int * pointers and char * pointers aren't the same).
Value-initialization of a pointer initializes it to a null pointer value; therefore both initializer lists are equivalent.
Pointers don't have class or array type, so value initialization for them is zero initialization. (8.5p8)
Then, (8.5p6)
To zero-initialize an object or reference of type
T
means:
- if
T
is a scalar type (3.9), the object is initialized to the value obtained by converting the integer literal0
(zero) toT
This integer literal 0
is a null pointer constant (4.10p1), which when converted to a pointer type creates a null pointer value.
Note that zero-initialization of variables with static and thread duration (3.6.2) also initializes pointers to null pointer values.
Above paragraph references are from C++1y draft n3936, but they were the same in earlier drafts I checked also.
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