On Dec 11, 7:28 pm, Rahul <sam_...@yahoo.co.inwrote:
I have the following code,
class B;
class A
{
public : operator B();
};
class B
{
public : B()
{
}
B(const A& ref)
{
printf("destination conversion\n");
}
B(const B& ref)
{
printf("copy constructor\n");
}
};
A::operator B()
{
printf("source conversion\n");
return B();}
int main()
{
A obj;
B obj1 = obj;
return(0);
}
so the output is
destination conversion.
There are actually two ways to convert from obj to obj1
1) destination conversion, constructor function of B
2) source conversion, operator function of A and then copy constructor
of B
The compiler has selected the first option, where as I
expected a ambiguity compile time error, what does the
standard say for this?
That you should see "source conversion" (which is also what I
get from g++ and Sun CC). The requirement in "B obj1 = obj;" is
that obj must be converted into a B (which is then used as an
argument for the copy constructor). A::operator B() is an exact
match, in every detail. B( A const& ) is classified as an exact
match, but does require adding a const, which in this case, the
compiler shoul use as a tie-breaker.
Change the code to:
A const obj ;
B obj1 = obj ;
and you should see "destination conversion", since A::operator
B() can no longer be called on obj. (You'll also have to
provide a user defined default constructor for A.)
Declare A::operator B() const (which it probablyl should be),
and the conversions will be ambiguous (but g++ allows it, using
"destination conversions"---an error in g++).
In practice, of course, it shouldn't matter---you should never
provide round-trip implicit conversions anyway.
--
James Kanze (GABI Software) email:ja*********@gmail.com
Conseils en informatique orientée objet/
Beratung in objektorientierter Datenverarbeitung
9 place Sémard, 78210 St.-Cyr-l'École, France, +33 (0)1 30 23 00 34