Skip to content

Two routes for implicit type conversion

Question

Given C++ classes A and B, what are the two mechanisms that allow an A to be converted to a B implicitly?

Short answer

A converting constructor in B or a conversion operator in A. Either B has a non-explicit constructor callable with one A argument, such as B(const A&), or A defines operator B() const. Mark them explicit when silent conversions would be surprising, and avoid defining both, which makes conversions ambiguous.

Adapted from Joshi, Denson & Downes, Quant Job Interview Questions and Answers, Q7.15, p.226; question and answer rewritten by SelfMadeQuant.com.

Reveal 10 worked solutions and unlock TENALPHA ($99 → $69/month)

Open the worked solution

Lessons behind this question