Before C++11, the NULL identifier was meant to be used for pointers. In this recipe, we'll see why this was a problem and how C++11 solved it.
Learning how nullptr works
How to do it...
To understand why nullptr is important, let's look at the problem with NULL:
- Let's write the following code:
bool speedUp (int speed);
bool speedUp (char* speed);
int main()
{
bool ok = speedUp (NULL);
}
- Now, let's rewrite the preceding code using nullptr:
bool speedUp (int speed);
bool speedUp (char* speed);
int main()
{
bool ok = speedUp (nullptr);
}
How it works...
The first program might not compile or (if it does) call the wrong method. We would expect it to call bool speedUp (char* speed); instead. The problem with NULL was exactly this: NULL was defined as 0, which is an integer type, and used by the pre-processor (which was replacing all the occurrences of NULL with 0). This is a huge difference as nullptr is now among the C++ primitives types and managed by the compiler.
For the second program, the speedUp (overloaded) method is called with the char* pointer to nullptr. There is no ambiguity here – we're calling the version with the char* type.
There's more...
nullptr represents a pointer that does not point to any object:
int* p = nullptr;
Due to this, there is no ambiguity, which means that readability improves. Another example that improves readability is as follows:
if (x == nullptr)
{
// ...\
}
This makes the code more readable and clearly indicates that we're comparing a pointer.
See also
The books Effective Modern C++ by Scott Meyers and The C++ Programming Language by Bjarne Stroustrup cover these topics in great detail.