Learn++ Lesson 46: The Explicit Keyword in C++ Programming
In C++, the explicit keyword prevents a single-argument constructor from being used for unintended implicit conversions. This keeps object construction deliberate and clear.
Use an explicit constructor
#include <iostream>
class Box {
public:
explicit Box(int l) : length(l) {}
private:
int length;
};
int main() {
// Box b = 10; // Invalid implicit conversion.
Box b(10); // Direct initialization is valid.
return 0;
}
Output:
(no output)
The constructor is marked explicit, so Box b = 10 is rejected while Box b(10) is accepted. The explicit form prevents accidental conversions and makes the programmer's intent visible.
Why explicit matters
- It prevents accidental conversions from a single value to a class object.
- It makes construction syntax intentional and easier to review.
- It helps the compiler catch unintended type conversions.
What you practice in the app
- Declaring an
explicitconstructor. - Distinguishing direct initialization from implicit conversion.
- Recognizing how
explicitimproves type safety.
Today's challenge
Fill in the missing constructor name. The completed program must compile and print 10:
#include <iostream>
class Box {
public:
explicit ___(int l) : length(l) {}
int getLength() const { return length; }
private:
int length;
};
int main() {
// Box b = 10; // Invalid implicit conversion.
Box b(10);
std::cout << b.getLength();
return 0;
}
The unique intended answer is Box, the constructor name required by the Box class.