![]() |
VOOZH | about |
The explicit keyword in C++ is used to prevent the compiler from performing automatic type conversions through constructors or conversion operators. It ensures that object creation and type conversion happen only when explicitly requested by the programmer.
When a constructor accepts a single argument, the compiler can automatically use it for type conversion. This behavior may sometimes lead to unexpected results.
Example: Without explicit
Constructor Called: 10
The explicit keyword prevents automatic conversions and requires direct object creation.
Syntax:
explicit ConstructorName(parameters);
Constructor Called: 10
Explanation: The object is created directly using the constructor because implicit conversion is not allowed.
Output:
Compilation Error
Explanation: The statement Number n = 10; attempts an implicit conversion from int to Number. Since the constructor is marked as explicit, the compiler generates an error.
Student ID: 101 Student Name: Rahul
Explanation: The integer constructor requires explicit object creation, while the string constructor can still be used for implicit conversions.
Starting from C++11, the explicit keyword can also be applied to conversion operators.
True
Explanation: The object is explicitly converted to bool using static_cast, preventing accidental conversions.