NULL in C++

A raw pointer is usually initialized to the value of NULL in C++:

int* aNum = NULL;

This indicates that the pointer aNum points to the value of 0 in most implementations. It can be thought of as a 0 in mathematics, where the length of the following vector is 0 and the direction is undefined. Similarly, aNum in the above statement is pointing to an undefined value. So, dereferencing aNum leads to a segmentation fault or access violation.

In C++11, a nullptr constant has been introduced that can be implicitly converted to any pointer type.

int* aNum = nullptr;

A possible implementation for NULL is:

#define NULL 0       // Implementation prior to C++11
#define NULL nullptr // Implementation since C++11
typedef decltype(nullptr) std::nullptr_t;

The first definition above can lead to ambiguity in the following code:

void aFunction(MyClass *);  // MyClass is a user defined class
void aFunction(int);        // overloaded function that takes an int
MyClass* anInstance = NULL; // Prior to C++11 implementation of NULL
aFunction(anInstance);

The above call to aFunction(anInstance) will call aFunction(int), because NULL resolves to 0 and will cause unintentional behavior. In C++11 implementation of NULL, aFunction(anInstance) will resolve to aFunction(MyClass*) because NULL resolves to nullptr which resolves to MyClass* type.

Leave a Reply

Your email address will not be published. Required fields are marked *