C++ 11 feature: nullptr

“nullpt” is a new concept that has been introduced in C++ 11.

Earlier to C++ 11, NULL has been defined as:

#define NULL 0

But after C++ 11, NULL has been defined as

#define NULL nullptr

“nullptr” is defined in #include <cstddef> header file.

It means earlier to C++ 11, the NULL will be converted to interger literal 0. So it will become difficult for overloaded function that accepts NULL and integer 0.

For example:

#include <iostream>

using namespace std;
//for more C++ tutorial visit www.ProDeveloperTutorial.com

void fun(int num)
{
    cout<<"Int func"<<endl;
}

void fun(char *s)
{
    cout<<"Char func"<<endl;
}

int main()
{
    fun(NULL);
    
    return 0;
}

Output:

main.cpp: In function ‘int main()’:
main.cpp:26:13: error: call of overloaded ‘fun(NULL)’ is ambiguous
     fun(NULL);
             ^
main.cpp:13:5: note: candidate: int fun(int)
 int fun(int num)
     ^~~
main.cpp:18:5: note: candidate: int fun(char*)
 int fun(char *s)
     ^~~

You will get an error as above.

It means that NULL is convert to ‘0’ and compiler is in ambiguity on which function to call.

So to solve these kind of issues, C++ 11 onwards, they have introduced “nullptr”.

So now when you call fun(nullptr); char function will be called.

Example:

#include <iostream>

using namespace std;
//for more C++ tutorial visit www.ProDeveloperTutorial.com

void fun(int num)
{
    cout<<"Int func"<<endl;
}

void fun(char *s)
{
    cout<<"Char func"<<endl;
}


int main()
{
    fun(nullptr);
    
    return 0;
}

Output:

Char func

“nullptr” can be converted to any pointer or pointer to member type. “nullptr” cannot be implicitly convertable or comparable to integral type.

Example:

#include <iostream>

using namespace std;
//for more C++ tutorial visit www.ProDeveloperTutorial.com

int main()
{
    int x = NULL; // works

    int x1 = nullptr; // error.  
    
    return 0;
}

Error:

Main.cpp:10:9: error: cannot initialize a variable of type 'int' with an rvalue of type 'nullptr_t'
    int x1 = nullptr; // error.  

“nullptr” is convertable to bool.

#include <iostream>

using namespace std;
//for more C++ tutorial visit www.ProDeveloperTutorial.com

int main()
{
    int *ptr = nullptr;
    
    if (ptr) 
    { 
        cout << "true"<<endl; 
    }     
   
   else 
   { 
       cout << "false"<<endl; 
   }  
    return 0;
}

Output:

false

You can also create a nullptr variable as below:

nullptr np1, np2;

Final Example:

#include <iostream>
#include <cstddef> 
using namespace std;
//for more C++ tutorial visit www.ProDeveloperTutorial.com

void fun(int *num)
{
    cout<<"Int func"<<endl;
}

void fun(char *s)
{
    cout<<"Char func"<<endl;
}



int main()
{
    int *ptr = nullptr;
    
    fun(ptr);
    
    char *cptr = nullptr;
    fun(cptr);
    
    return 0;
}

Output:

Int func
Char func
Write a Comment

Leave a Comment

Your email address will not be published. Required fields are marked *