What is the main purpose of the explicit keyword with a C++ constructor?

Options

  • A. To prevent unwanted implicit conversions
  • B. To make the constructor virtual
  • C. To automatically create a destructor
  • D. More than one of the above
  • E. None of the above

Correct Answer (Detailed Explanation is Below)

A. To prevent unwanted implicit conversions

Detailed Explanation

Answer: (A) To prevent unwanted implicit conversions

The explicit keyword can be used with a constructor to prevent certain unwanted implicit conversions.

For example, a single-argument constructor can otherwise sometimes be used for implicit conversion from the argument type to the class type.

Declaring the constructor as explicit requires the programmer to explicitly create the object instead of allowing such implicit conversion.

This improves type safety and makes the programmer's intention clearer.