explicit c++

explicit in C++

#include <iostream>
using namespace std;

class A {
public:
    A(int) {}
};

void func(const A& a) {
    cout << "func called" << endl;
}

int main() {
    func(10);
    return 0;
}

Explanation:

In this example, the explicit keyword is used in the constructor of class A to prevent implicit conversions. The constructor A(int) is marked as explicit, which means that it cannot be used for implicit conversions. In the main function, when func(10) is called, it tries to pass an int to the func function, which expects an object of type A. Since the constructor of A is marked as explicit, the compiler will not perform implicit conversion from int to A, and an error will be generated.