user1899020
user1899020

Reputation: 13575

Constructor or conversion is called?

For example

struct A
{
    A(B const& b) {}  // function 1
};

struct B
{
    operator A() const { return A(); } // function 2
};

And

B b;
A a(b); // function 1 is called.

Any way to make a to be constructed or converted by function 2?

Upvotes: 0

Views: 39

Answers (1)

David
David

Reputation: 28178

The way you've written it, overload resolution choses A's ctor. If you wrote it slightly differently:

A a = b

It would cause an error that the conversion is ambiguous. If you changed A's ctor to be explicit:

explicit A(const B&) {}

It would then choose B's conversion operator instead of A's ctor with the line A a = b, and call A's ctor with the line A a(b)

If you really want to force B's conversion operator, you can always call it explicitly:

A a = b.operator A();

Upvotes: 2

Related Questions