Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

default parameters in c++

Tags:

c++

Consider the following:

int foo(int x , int z = 0);
int foo(int x, int y , int z = 0);

If I call this function like so:

foo( 1 , 2);

How does the compiler know which one to use?

like image 427
James Allan Avatar asked Apr 02 '12 09:04

James Allan


1 Answers

It won't and hence this example will not compile cleanly, it will give you an compilation error.
It will give you an ambiguous function call error.

Online Sample:

int foo(int x , int z = 0){return 0;} 
int foo(int x, int y , int z = 0){return 10;}

int main()
{
    foo( 1 , 2); 
    return 0;
}

Output:

prog.cpp: In function ‘int main()’:
prog.cpp:6: error: call of overloaded ‘foo(int, int)’ is ambiguous
prog.cpp:1: note: candidates are: int foo(int, int)
prog.cpp:2: note: int foo(int, int, int)

like image 163
Alok Save Avatar answered Oct 09 '22 16:10

Alok Save