C++ explicit Keyword
Example
An explicit constructor must be called with parentheses:
class Box {
public:
int size;
explicit Box(int s) {
size = s;
}
};
int main() {
Box box1(5); // OK
// Box box2 = 5; // Error, because the constructor is explicit
cout << box1.size;
return 0;
}
Definition and Usage
The explicit keyword is used in front of a constructor. It means that the constructor can only be called on purpose, like Box box1(5);.
Without explicit, C++ could also use the constructor to change an int into a Box automatically, so Box box2 = 5; would work. This automatic change can hide mistakes.
Related Pages
Read more about constructors in our C++ Constructors Tutorial.