0

Pointers present some special problems for overload resolution.

Say for example,

void f(int* x) { ... }
void f(char* x) { ...}
int main()
{
    f(0);
}

What is wrong with calling f(0)? How can I fix the function call for f(0)?

3 Answers 3

6

f((int*) 0) or f((char *) 0)

But if you find yourself doing this I would take another look at your design.

Sign up to request clarification or add additional context in comments.

4 Comments

Is it because chars are represented as numbers or?
It is because you can't infer the type from just a zero
0 means null pointer in C++. So it could be a null int* or a null char*. Compiler can't determine which one.
Technically, it's a "null pointer constant", not a "null pointer". All pointers, including null pointers are have pointer type. Null pointer constants are integral constants.
0

Cast it, or don't use it at all:

f((int*)0);

Comments

0

What is wrong with calling f(0) is the resolution is ambiguous. Both of your overloaded functions take a pointer which in this case can only be resolved via cast.

f((int*)0)

Depending on what you're trying to do here there are other options that are not ambiguous.

Comments