iammilind
iammilind

Reputation: 69988

Why typecasting operator doesn't work with inherited class?

I have two classes:

struct B {};
struct D {
  operator B& ();
};

When I do;

b = d; // B b; ... D d;

Result is as per expectation where D::operator B&() is invoked (Demo).

If the D is changed to,

struct D : B {
  operator B& ();
};

then D::operator B&() is not invoked (Demo). Is B::B(const B&) is finding a better candidate in D then D::operator B&() ?

Upvotes: 5

Views: 113

Answers (1)

Sven
Sven

Reputation: 22673

If D derives from B, there is an implicit automatic conversion from D to B. This has higher precedence than a user-defined conversion operator.

Upvotes: 7

Related Questions