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
C++ Classes and Objects
C++ Constructors and Destructors
C++ Access Specifiers and Encapsulation
C++ Inheritance
C++ Polymorphism and Virtual Functions
C++ Abstract Classes and Interfaces
C++ Operator Overloading
Exercises & Assignments
Build a BankAccount class
Calculate areas with polymorphism
Overload operators for a Money class
Interview Questions & Answers
What is the difference between struct and class in C++?
What is a constructor in C++ and what are its types?
What is a destructor in C++?
What is the difference between overloading and overriding in C++?
What is a virtual function in C++?
What is a pure virtual function and an abstract class in C++?
What is the static keyword in C++?