Open In App

How to Prevent Implicit Conversions in C++?

Last Updated : 08 Apr, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

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:

C++
// C++ Program to demonstrate implicit conversion
#include <iostream>
using namespace std;

class Distance {
private:
    int meters;
public:
    Distance(int meters) : meters(meters) {}
    void display() const {
        cout << "Distance: " << meters << " meters\n";
    }
};

void printDistance(Distance d) {
    d.display();
}

int main() {
    int meters = 10;
    // Implicit conversion from int to Distance
    printDistance(meters); 
    return 0;
}

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++:

C++
// C++ Program to demonstrate how to prevent implicit
// conversions
#include <iostream>
using namespace std;

class Distance {
private:
    int meters;

public:
    // Make the constructor of the class explicit to prevent
    // implicit conversion
    explicit Distance(int meters): meters(meters) {}
    void display() const
    {
        cout << "Distance: " << meters << " meters\n";
    }
};

void printDistance(Distance d) { d.display(); }

int main()
{
    int meters = 10;
    // now the implicit conversion will not take place and
    // error will be thrown
    printDistance(meters);
    return 0;
}

Output

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



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads