What exactly is nullptr in C++?

C++Server Side ProgrammingProgramming

In this section we will see the nullptr in C++. The nullptr denotes the pointer literals. It is a prvalue of type std::nullptr_t. It has implicit conversion property from nullptr to null pointer value of any pointer type and any pointer to member type. Let us see one program, to understand this concept.

Example

#include<iostream>
using namespace std;
int my_func(int N){ //function with integer type parameter
   cout << "Calling function my_func(int)";
}
int my_func(char* str) { //overloaded function with char* type parameter
   cout << "calling function my_func(char *)";
}
int main() {
   my_func(NULL); //it will call my_func(char *), but will generate compiler error
}

Output

[Error] call of overloaded 'my_func(NULL)' is ambiguous
[Note] candidates are:
[Note] int my_func(int)
[Note] int my_func(char*)

So what is the problem in the above program? The NULL is typically defined as (void*)0. We are allowed to convert NULL to integral type. So the function call of my_func(NULL) is ambiguous.

If we use the nullptr in the place of NULL, we will get the result like below −

Example

#include<iostream>
using namespace std;
int my_func(int N){ //function with integer type parameter
   cout << "Calling function my_func(int)";
}
int my_func(char* str) { //overloaded function with char* type parameter
   cout << "calling function my_func(char *)";
}
int main() {
   my_func(nullptr); //it will call my_func(char *), but will generate compiler error
}

Output

calling function my_func(char *)

We can use the nullptr at all places where NULL is expected. Like the NULL, the nullptr also can be converted into any pointer type. But this is not implicitly convertible to integral type like NULL.

raja
Published on 07-May-2019 12:02:54
Advertisements