ambiguity related to overloaded functions

S

subramanian100in

Consider the program

#include <iostream>

using namespace std;

void fn(const char * str, char x = 'Y')
{
cout << "from fn(const char *, char) - " << str << endl;
return;
}

void fn(const char * str)
{
cout << "from fn(const char *) - " << str << endl;
return;
}

int main( )
{
// fn("test string");
return 0;
}

This program compiles without any error or warning. If I remove the
comment in the statement
// fn("test string");
in main( ), I am getting ambiguity error. Why doesn't the compiler
detect the ambiguity even when the call to fn( ) was not made ? What
is the expected behaviour ? Where am I going wrong ?

Kindly explain.

Thanks
V.Subramanian
 
Z

Zara

Consider the program

#include <iostream>

using namespace std;

void fn(const char * str, char x = 'Y')
{
cout << "from fn(const char *, char) - " << str << endl;
return;
}

void fn(const char * str)
{
cout << "from fn(const char *) - " << str << endl;
return;
}

int main( )
{
// fn("test string");
return 0;
}

This program compiles without any error or warning. If I remove the
comment in the statement
// fn("test string");
in main( ), I am getting ambiguity error. Why doesn't the compiler
detect the ambiguity even when the call to fn( ) was not made ? What
is the expected behaviour ? Where am I going wrong ?

Ambiguity condition is tested only when the function is needed, that
is, when compiler tries to find an adequate funtiona for the call
If commented line were:
fn("test string",'N');
there would be no ambiguity at all.

Best regards,

Zara
 
A

Alan Johnson

Consider the program

#include <iostream>

using namespace std;

void fn(const char * str, char x = 'Y')
{
cout << "from fn(const char *, char) - " << str << endl;
return;
}

void fn(const char * str)
{
cout << "from fn(const char *) - " << str << endl;
return;
}

int main( )
{
// fn("test string");
return 0;
}

This program compiles without any error or warning. If I remove the
comment in the statement
// fn("test string");
in main( ), I am getting ambiguity error. Why doesn't the compiler
detect the ambiguity even when the call to fn( ) was not made ? What
is the expected behaviour ? Where am I going wrong ?

Kindly explain.

Thanks
V.Subramanian

Because functions themselves are not ambiguous. Calls to functions can
be. Even in this program it would be possible to call the second
version of fn unambiguously. One method of doing so might be:
void (*p)(const char * str) = fn ;
p("test string") ;
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,766
Messages
2,569,569
Members
45,042
Latest member
icassiem

Latest Threads

Top