![]() |
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 ConversionsThe below example demonstrates how to prevent implicit conversions in C++:
Output main.cpp: In function ‘int main()’: |
Reffered: https://www.geeksforgeeks.org
C++ Programs |
Type: | Geek |
Category: | Coding |
Sub Category: | Tutorial |
Uploaded by: | Admin |
Views: | 17 |