LearnFrenzy
Sign in Take a free test

Operator Overloading · Find the Error · Question 6

Error: using an explicit conversion implicitly Answer, explanation & discussion

  • Find the error
  • Medium
  • 0 comments
  • Answer explained
  • Moderated community
Question 6 Back to Exercise

The program below does not compile. Which statement correctly describes the problem?

main.cpp
#include <iostream>

struct Celsius {
    double v;
    explicit operator double() const { return v; }
};

int main() {
    Celsius t{36.6};
    double d = t;
    std::cout << d << '\n';
    return 0;
}
  • A v must be float
  • B The conversion operator is explicit, so double d = t is not allowed; write static_cast<double>(t) Correct
  • C Celsius needs a constructor
  • D operator double must be static
Correct Answer: Option B

Only contextual bool conversions are allowed implicitly for explicit operators – and this is a double.

Discussion & Comments 0

Share your method, a shortcut, or ask about a step you didn't follow.

No comments yet. Be the first to share your solution!

Post your comment

Comments appear after a quick review by our team.

Search LearnFrenzy

Esc

Quick links