After reading this, I tried to do such a conversion using static_cast :
class A; class B { public: B(){} B(const A&) //conversion constructor { cout << "called B conversion constructor" << endl; } }; class A { public: operator B() const //conversion operator { cout << "called A conversion operator" << endl; return B(); } }; int main() { A a; //Original code, This is ambiguous, //because both operator and constructor have same cv qualification (use -pedantic flag) B b = a; //Why isn't this ambiguous, Why is conversion constructor called, //if both constructor and operator have same cv qualification B c = static_cast<B>(a); return 0; }
I expected it to not compile because both the constructors and the operators have the same cv qualifications. However, it compiled successfully and static_cast calls the constructor instead of the statement. What for?
(compiled using gcc 4.8.1 with pedantic and Wall flags)
c ++ gcc casting static-cast
PcAF
source share