Static_cast Conversion Constructor vs Conversion Operator

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)

+8
c ++ gcc casting static-cast
source share
1 answer

The C ++ 11 standard says (focus):

5.2.9 Static casting

4 Otherwise, the expression e can be explicitly converted to type T using static_cast form static_cast<T>(e) if the declaration is T t(e); is correct for some invented time variable T (8.5). The effect of such an explicit conversion is the same as executing a declaration and initialization, and then using a temporary variable as a result of the conversion. The expression e used as a glvalue if and only if initialization uses it as a glvalue.

5 Otherwise, static_cast must perform one of the following transformations. No other conversion should be performed explicitly with static_cast .

This explains why static_cast in

 B c = static_cast<B>(a); 

ends with a call to constructor B

The conversion operator is used only if T t(e) not correctly formed.

+8
source share

All Articles