Maestro
Maestro

Reputation: 2552

C++ primer 5 ed. mutual conversions

I have some difficulty to understand mutual conversions, it is explained in C++ Primer 5 ed.:

"In the following example, we’ve defined two ways to obtain an A from a B: either by using B’s conversion operator or by using the A constructor that takes a B:// usually a bad idea to have mutual conversions between two class types:

struct B;
struct A {
A() = default;
A(const B&);        // converts a B to an A
// other members
};

struct B {
    operator A() const; // also converts a B to an A
    // other members
};

A f(const A&);
B b;
A a = f(b); // error ambiguous: f(B::operator A())
        //          or f(A::A(const B&))

Because there are two ways to obtain an A from a B, the compiler doesn’t know which conversion to run; the call to f is ambiguous. This call can use the A constructor that takes a B, or it can use the B conversion operator that converts a B to an A. Because these two functions are equally good, the call is in error.

If we want to make this call, we have to explicitly call the conversion operator or the constructor:

A a1 = f(b.operator A()); // ok: use B's conversion operator 
A a2 = f(A(b));           // ok: use A's constructor

Note that we can’t resolve the ambiguity by using a cast—the cast itself would have the same ambiguity."

Upvotes: 2

Views: 71

Answers (1)

eerorika
eerorika

Reputation: 238311

But when I defined the required members and f I don't get any error!

The shown program is ill-formed for the reasons described in the book. If a compiler fails to issue a diagnostic message, then the compiler does not conform to the standard.

I am using GCC.

You can ask GCC to try to conform to the C++ standard using the -pedantic option. Unfortunately, it will otherwise enable some language extensions by default.

Upvotes: 6

Related Questions