After reading this I tried making such conversion with static_cast
:
class A;
class B {
public:
B(){}
B(const A&) //conversion constructor
{
cout << "called B's conversion constructor" << endl;
}
};
class A {
public:
operator B() const //conversion operator
{
cout << "called A's 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 c-v qualification
B c = static_cast<B>(a);
return 0;
}
I expected it to not compile, because both constructor and operator have same c-v qualification. However it compiled, successfully and static_cast
calls constructor instead of operator. Why?
(compiled using gcc 4.8.1 with pedantic
and Wall
flags)