
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
What Exactly is nullptr in C++
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.