Reading some questions here about SO about conversion operators and constructors made me think about the interaction between them, namely, when there is an “ambiguous” call. Consider the following code:
class A; class B { public: B(){} B(const A&) //conversion constructor { cout << "called B conversion constructor" << endl; } }; class A { public: operator B() //conversion operator { cout << "called A conversion operator" << endl; return B(); } }; int main() { B b = A(); //what should be called here? apparently, A::operator B() return 0; }
In the above code, a “called conversion operator” is displayed, which means that the conversion operator is invoked in contrast to the constructor. If you remove / comment out the operator B() code from A , the compiler will happily switch to using the constructor (without any code changes).
My questions:
- Since the compiler does not consider that
B b = A(); is an ambiguous call, there must be some type of priority. Where exactly is this priority set? (a score / quote from a C ++ standard would be appreciated) - From an object-oriented philosophical point of view, does the code do this? Who knows more about how object
A should become object B , A or B ? According to C ++, the answer is A - is there anything in object-oriented practice that suggests this should be so? For me personally, this would make sense anyway, so I am interested to know how the choice was made.
Thank you in advance
c ++ operators constructor type-conversion conversion-operator
GRB Sep 05 '09 at 18:47 2009-09-05 18:47
source share