What is Explicit Specifier ? How can we use Explicit Specifiers in Classes ? Here are the explanations with examples below,
Classes are are the blueprint that has properties and methods for the objects and they are user-defined data types that we can use in our program, and they work as an object constructor. Classes defined in C++ by using keyword class followed by the name of the class.
Objects are an instantiation of a class, In another term. In C++ programming, most of the commands are associated with classes and objects, along with their attributes and methods.
The Explicit Specifier defined with ‘explicit‘ statement and it can be used alone or with a constant expression in C++ Classes that the function is explicit if and only if that constant expression evaluates to true. It specifies that a constructor or conversion function or deduction guide is explicit. It cannot be used for implicitly conversions and copy initialization.
Syntax,
1 2 3 |
explicit; |
1 2 3 |
explicit ( expression ); |
An example in a Class,
1 2 3 4 5 6 7 8 9 |
class myclass { public: explicit myclass(const myclass&) // Compatible with C++17 (Error in C++20) { }; }; |
An example with ‘operator’ statement in a Class,
1 2 3 4 5 6 7 |
class myclass { public: explicit operator int (); // Compatible with C++17 (Error in C++20) }; |
The explicit specifier may only appear within the decl-specifier-seq of the declaration of a constructor or conversion function within its class definition.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
struct myclass1 { explicit myclass1 (int) { } explicit myclass1 (int, int) { } explicit operator bool() const { return true; } }; int main() { // myclass b1 = 1; // Error myclass b2(2); // Correct myclass b3 {4, 5}; // Correct // myclass b4 = {4, 5}; // Error myclass b5 = (B)1; // Correct if (b2) return; // Correct // bool nb1 = b2; // Error bool nb2 = static_cast<bool>(b2); // Correct return 0; } |
Get started building powerful apps with C++Builder!
Design. Code. Compile. Deploy.
Start Free Trial
Free C++Builder Community Edition