Is this ambiguous?

A

Alan Johnson

Consider the following code, with the interesting lines numbered in
comments:

class A
{
public :

bool f(int level = 1) // line 5
{ return true ; }

void f(bool val, int level = 1)
{}

} ;

class B
{
private :
A *a ;
public :
bool f(int level = 1) // line 18
{ return a->f(level) ; } // line 19

void f(bool val, int level = 1)
{ a->f(val, level) ; }
} ;


This compiles fine for me (gcc 3.4.4). However, if I make the functions
on line 5 and line 18 const, then my compiler says the function call on
line 19 is ambiguous. It makes sense to me why it would be ambiguous
(level is convertible to bool, and so it might could match f(bool, int)
since the int parameter has a default value). However, what I don't
understand is why it is NOT ambiguous without the const. Any insight?

-Alan
 
A

Alf P. Steinbach

* Alan Johnson:
Consider the following code, with the interesting lines numbered in
comments:

class A
{
public :

bool f(int level = 1) // line 5
{ return true ; }

void f(bool val, int level = 1)
{}

} ;

class B
{
private :
A *a ;
public :
bool f(int level = 1) // line 18
{ return a->f(level) ; } // line 19

void f(bool val, int level = 1)
{ a->f(val, level) ; }
} ;


This compiles fine for me (gcc 3.4.4). However, if I make the functions
on line 5 and line 18 const,

The one on line 18 doesn't matter.
then my compiler says the function call on
line 19 is ambiguous. It makes sense to me why it would be ambiguous
(level is convertible to bool, and so it might could match f(bool, int)
since the int parameter has a default value). However, what I don't
understand is why it is NOT ambiguous without the const. Any insight?

First, be clear that result types are not considered in overload
resolution, and that making the function on line 18 const does not
make the object pointed to by 'a' const.

Without the const on line 5 the compiler has a choice between no
conversion, and conversion of the argument to bool. The no-conversion
is clearly better. Hence the first function is selected.

With the const on line 5 either 'a*' must be converted to
'a const*', or int must be converted to bool. I don't recall the
exact rules, but at least there are now two possible conversions. It
surprises me that the to-const conversion should weight in as much
as a possible value representation change (and a lossy one, at that!),
but then, the C++ rules are evolved beasts with lots of non-optimum
and counter-intuitive consequences.
 

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

Forum statistics

Threads
473,768
Messages
2,569,575
Members
45,053
Latest member
billing-software

Latest Threads

Top