Prevent implicit conversions using the `explicit` keyword
By default, a constructor that can be called with a single argument acts as a conversion operator, allowing the compiler to implicitly convert one type to another. To prevent this and force the developer to use explicit initialization, use the
explicit keyword. This is particularly useful for ensuring that function arguments are of the exact intended type and not implicitly converted from another class.#include <iostream>
class A {};
class B {
public:
// Marking constructor as explicit prevents implicit conversion from A to B
explicit B(const A& x) {}
B& operator= (const A& x) { return *this; }
operator A() { return A(); }
};
void fn(B x) {}
int main() {
A foo;
// B bar = foo; // ERROR: Implicit conversion is forbidden by 'explicit'
B bar(foo); // OK: Explicit initialization
bar = foo; // OK: Assignment operator is not affected by 'explicit' constructor
foo = bar; // OK: Uses type-cast operator
// fn(foo); // ERROR: Cannot implicitly convert A to B for function argument
fn(bar); // OK
return 0;
}