What is the explicit keyword in C++?

#include <iostream>

struct Meters {
    explicit Meters(double v) : value(v) {}
    double value;
};

void show(Meters m) { std::cout << m.value << '\n'; }

int main() {
    show(Meters(5));        // fine
    show(5);                // error: the hidden conversion is not allowed
}
Output

Implicit.cpp: In function 'int main()':
Implicit.cpp:12:10: error: could not convert '5' from 'int' to 'Meters'
12 | show(5); // error: the hidden conversion is not allowed
| ^
| |
| int
Implicit.cpp:4:14: note: explicit conversion function was not considered
4 | explicit Meters(double v) : value(v) {}
| ^~~~~~

Without explicit, show(5) would compile and quietly create a Meters. Mark single argument constructors explicit unless you really want the conversion. See Constructors.


Learn more about the similar topics:
Tutorials
No Content Found.
Exercises & Assignments
No Content Found.
Interview Questions & Answers
No Content Found.