2.1.2 std::nullptr_t and nullptr

What was the problem

The traditional way to set a pointer to zero before C++11 was via the NULL macro. So what would happen if we tried to compile the following program?

#include <cstddef> 
 
void foo(int) {} 
void foo(int*) {} 
 
int main(int argc, char** argv) 
{ 
  foo(NULL); 
  return 0; 
}

Did you expect the program to compile well and foo(int*) to be called? Too bad, we are in a good old ambiguous call situation:

error: call of overloaded foo(NULL) is ambiguous

Since NULL is often defined as the integral value zero, the compiler cannot distinguish it from an integer. Thus the error.

How the Problem is Solved

PIC <cstddef>

As an answer to this problem, C++11 introduces the nullptr keyword, which exactly represents a zero pointer. Its type is std::nullptr_t and it is implicitly convertible to any pointer. Consequently, the code below compiles as expected.

void foo(int) {} 
void foo(int*) {} 
 
int main(int argc, char** argv) 
{ 
  foo(nullptr); 
 
  return 0; 
}

Note that nullptr is a keyword available without prior definition. Its type, on the other hand, is defined in header cstddef.