Compiler chooses conv ctor - why?



Hello,

In the following code conversion from class A object to class B object can be done in two ways: (1) by conversion function being member of class A (line 6); (2) by conversion constructor being member of class B (line 11). However conversion constructor is called. The sole way to make A::operator B() to be called is removing ,,const'' qualifiers (at lines 11 & 25). This causes that the only implicit conversion sequence goes throughout conversion function (declared at line 6). Why? It seems that according to 13.3 of ISO 14882 none of the sequences is better then other. Thus ambiguity should occur causing error. Could somebody point out what part of ISO 14882 causes that conversion constructor (and not conv foo) should be chosen and why conv ctor is better then conv foo?

-- best regards

Cezary Noweta

======
#include <stdio.h>

struct B;

struct A {
operator const B() const; // Line 6
};

struct B {
B();
B(const A& a); // Line 11
const B& operator=(const B&) const;
};

A::operator const B() const
{
printf("conv foo called\n");
return(B());
}

B::B()
{
}

B::B(const A& a) // Line 25
{
printf("conv ctor called\n");
}

const B& B::operator=(const B&) const
{
return(this[0]);
}

const B foo(const A a)
{
return(a);
}

const B foo1(const A a)
{
return((const B)a);
}

const B foo2(const A a)
{
return(const B(a));
}

main()
{
const A a;
const B b;

b = foo(a);
b = foo1(a);
b = foo2(a);
}
======

.



Relevant Pages

  • Re: Anders Hejlsberg comment on immutable objects
    ... Immutability is a design goal that is achieved by use ... >>const, not an effect or result of const itself. ... I define improper as any conversion not fitting ... Unless the ability to cast away const was removed as you've ...
    (microsoft.public.dotnet.languages.csharp)
  • Re: Compiler chooses conv ctor - why?
    ... struct A { ... conversion function should be chosen, as according to 13.3.3.2of the standard, it is better function due to qualification conversion required by conversion constructor? ...
    (microsoft.public.vc.language)
  • Re: So many string types!
    ... > complains that it can not convert CHString to LPSTR. ... other .NET-languages only have one string type. ... AFAIK fopen expects a const char*, ... string class I know has a conversion to one of these types. ...
    (microsoft.public.dotnet.general)
  • Re: Operator overloading, well member function overload in general.
    ... It will also work if I remove the "const" modifier. ... that it's a const function requires a const conversion for the _object_ ... The compiler cannot decide. ... This is standard behaviour. ...
    (microsoft.public.vc.language)
  • Re: Smart pointers of const objets
    ... The problem is that you cannot bind a temporary object to a non-const ... the matching type) to a non-const reference. ... It will bind to a const reference though: ... Your conversion technique is actually ...
    (comp.lang.cpp)