Consider the following class definitions of A and B:
class A {
public:
void func() const {}
};
class B {
public:
// user-defined conversion operator to A
operator A() const { return a_; }
private:
A a_;
};
The class A defines a public member function called func(). The class B does not, but it does define a user-defined conversion operator to the type A. This way, an instance of B can be converted into an instance of A. The following code works as expected:
B b;
static_cast<A>(b).func(); // call func() on temporary instance of A
In the code above, the conversion operator is implicitly called by means of the static_cast named cast.
Note that the conversion operator in B is not specified as explicit in order to allow implicit conversions as well.
However, the following code does not compile:
B b;
b.func(); // <-- error: 'class B' has no member named 'func'
Just as the error message says, class B has no member named func, but class A does, and class B does have a user-defined conversion operator to A. The user-defined conversion operator is not implicitly called in this case.
Why is the conversion not being implicitly done?
b(1)orb+1etc., the compiler will in fact try all 30 conversion operators. There's just something different about the.operator. - aschepler