Let's have this code:
Test1 t1;
Test2 t2;
t1 = t2;
I believe there are three (or more?) ways how to implement t1 = t2
- to overload assign operator in
Test1
- to overload type cast operator in
Test2
- to create
Test1(const Test2&)
conversion constructor
According to my GCC testing, this is the priority of what is used:
- assign operator
- conversion constructor and type cast operator (ambiguous)
- const conversion constructor and const type cast operator (ambiguous)
Please help me understand why this priority.
I use this code for testing (uncomment some lines to try out)
struct Test2;
struct Test1 {
Test1() { }
Test1(const Test2& t) { puts("const constructor wins"); }
// Test1(Test2& t) { puts("constructor wins"); }
// Test1& operator=(Test2& t) { puts("assign wins"); }
};
struct Test2 {
Test2() { }
// operator Test1() const { puts("const cast wins"); return Test1(); }
// operator Test1() { puts("cast wins"); return Test1(); }
};
int main() {
Test1 t1;
Test2 t2;
t1 = t2;
return 0;
}
Test1::Test1(const Test2&)
is not a "copy constructor", it is a "converting constructor". – Occasion