c++ pointer null vs nullptr

The nullptr keyword was introduced in C++11 and it is used to represent a null pointer. A null pointer is a special value that points to no object or function.

In contrast, the NULL macro was used in previous versions of C++ to represent a null pointer. However, NULL was actually an implementation-defined value that was usually defined as 0 or ((void*)0).

The main advantage of using nullptr over NULL is that nullptr has its own distinct type, std::nullptr_t, whereas NULL is simply defined as an integer constant with a value of zero. This means that nullptr can be used in contexts where a type is required, such as in function overloading or template specialization.

For example, consider the following function:

void foo(int);
void foo(char*);

void bar() {
    foo(nullptr);
}

In this case, the call to foo(nullptr) would call the function foo(char) because nullptr has the type std::nullptr_t, which matches the type char more closely than the type int.

Another advantage of nullptr is that it is not implicitly convertible to other pointer types, whereas NULL is implicitly convertible to integer types. This can help prevent certain types of bugs, such as accidentally passing a null pointer to a function that expects an integer argument.

Overall, nullptr is considered the recommended way to represent a null pointer in modern C++ code, as it provides better type safety and avoids potential issues with implicit conversions.