VOOZH about

URL: https://www.geeksforgeeks.org/cpp/how-to-prevent-implicit-conversions-in-cpp/

⇱ How to Prevent Implicit Conversions in C++? - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

How to Prevent Implicit Conversions in C++?

Last Updated : 23 Jul, 2025

In C++, implicit conversions are automatic type conversions that are performed by the compiler when a value is used with a compatible type. While they can be useful, they can also lead to unexpected results and bugs. Therefore, it is sometimes desirable to prevent implicit conversions. In this article, we will learn how to prevent implicit conversions in C++.

Example of Implicit Conversion:


Output
Distance: 10 meters

In the following example, the class Distance has a function printDistance that takes an object of type Distance as an argument. However, in the main function we have passed an integer to the function and the code got executed successfully because the compiler performed an implicit conversion from into to Distance.

Avoid Implicit Conversions in C++

To avoid implicit conversions in C++, we can use the explicit keyword. When the explicit keyword is used with a constructor or a conversion function,it prevent implicit conversion which are performed by the compiler automatically.

C++ Program to Prevent Implicit Conversions

The below example demonstrates how to prevent implicit conversions in C++:

Output

main.cpp: In function ‘int main()’:
main.cpp:27:19: error: could not convert ‘meters’ from ‘int’ to ‘Distance’
27 | printDistance(meters);
| ^~~~~~
| |
| int


Comment