NULL is a macro, which is typically defined as (void *(0)), and it is used to represent a null pointer by assigning the literal 0. However, one drawback of using NULL is that it is not type-safe. In C++, it is not recommended to use NULL for null pointers.
std::cout << "Function with int pointer called." << std::endl;
return 0;
}
int func(double* ptr)
{
std::cout << "Function with double pointer called." << std::endl;
return 0;
}
int main()
{
func(NULL); // This would lead to ambiguity
return 0;
}
In this example, there are two overloaded functions, func: one that takes an int* and another that takes a double*. If we call func(NULL), the compiler might not be able to determine which version of the function to call because NULL is essentially 0, and both int and double can be implicitly converted from 0. This can lead to ambiguity and potential issues.
To avoid such problems, it's better to use nullptr.
func(nullptr); // This is type-safe
Using nullptr ensures that the correct version of the overloaded function is called based on the type of the pointer.
Conclusion: NULL assigns a literal 0 while the nullptr is a keyword to initialize pointers in C++