I know that NULL is #defined to be 0. It seems to be an int
constant that gets converted to a pointer type. So what happens when there are two overloaded functions: one takes a pointer type, another takes an int
type. How does this work vs. nullptr
?
#include <iostream>
using namespace std;
void callMe(int* p)
{
cout << "Function 1 called" << endl;
}
void callMe(int i)
{
cout << "Function 2 called" << endl;
}
int main()
{
callMe(nullptr);
callMe(NULL);
return 0;
}
I know that callMe(nullptr)
will definitely call the first function. But which function will be called by callMe(NULL)
? I compiled this code on my computer. There was only one warning.
g++ -std=c++11 nullptr_type.cpp
nullptr_type.cpp: In function 'int main()':
nullptr_type.cpp:44:14: warning: passing NULL to non-pointer argument 1 of 'void callMe(int)' [-Wconversion-null]
callMe(NULL);
^
My code compiled without any problems, and when I run it I see that callMe(NULL)
called Function 2. Visual Studio also compiles the code and it calls Function 2.
However, when I try to compile my code on the online GeeksForGeeks IDE, I get some compiler errors.
https://ide.geeksforgeeks.org/UsLgXRgpAe
I want to know why these errors occur.
prog.cpp: In function 'int main()':
prog.cpp:17:13: error: call of overloaded 'callMe(NULL)' is ambiguous
callMe(NULL);
^
prog.cpp:4:6: note: candidate: void callMe(int*)
void callMe(int* p)
^
prog.cpp:9:6: note: candidate: void callMe(int)
void callMe(int i)
^
The same errors are generated by the online Ideone IDE and online TutorialsPoint CodingGround IDE. Is this actually defined behavior or not?
What about this scenario? Which functions will get called here?
#include <iostream>
using namespace std;
void callMe(int* p)
{
cout << "Function 1 called" << endl;
}
void callMe(char* cp)
{
cout << "Function 2 called" << endl;
}
void callMe(nullptr_t np)
{
cout << "Function 3 called" << endl;
}
void callMe(int i)
{
cout << "Function 4 called" << endl;
}
int main()
{
callMe(nullptr);
callMe(NULL);
return 0;
}
A more general question, but I think that this is where it is all going to: How do you know which function calls are ambiguous or not when overloading functions? I want to know the answer to this question in the context where there are multiple functions which are competitors for the argument. If there would have been only one function, it would take the argument without error. But what happens when several functions seem to be equally likely to take that argument?
The linked question is about using NULL
in C. My question is about C++. The C programming language does not have operator overloading, and hence most of the issues that I touched upon are only C++ specific things.
===========================================================================
This is a related question which explains the issue and the solution to it in detail. There's a lot of useful answers in that one.