Use of explicit keyword in C++In this article, we will discuss the explicit keyword in C++ with its example. The explicit keyword is used with constructors in C++ to prevent them from doing implicit conversions. A C++ explicit constructor is marked to not implicitly convert types. It is important because implicit conversions frequently produce unexpected consequences. If we have a constructor with a single parameter in a class, the constructor transforms the single argument to the class produced and becomes a conversion constructor. We use explicit keywords in C++ to avoid such implicit conversions. Working of C++ Explicit:First, let us define constructors in C++. Constructors are unique methods in C++. They are invoked automatically whenever a class object is created. Using constructors, we initialize the new object's data members. Now, we will look at implicit conversions and how they can be avoided using C++ explicit keywords. It occurs without our directly instructing the compiler. Converting one data type to another is referred to as casting. Without the explicit C++ compiler, the compiler can execute the conversion automatically, removing the requirement for us to perform casting. We tell the compiler not to execute any implicit conversions on a constructor by including the keyword explicitly before it. Instead of the compiler executing undesirable type operations, we want those constructs to be explicitly invoked. Examples:Explicit constructors can be defined in C++ to avoid implicit type conversions. While a constructor is made explicit, the compiler cannot conduct any implicit conversions while initializing an object using that constructor. Here are several C++ examples using explicit constructors: Example: Output: number1: 72 number2: 85 Explanation:
Uses of explicit keyword:
Next Topicwcrtomb() function in C/C++ |
We provides tutorials and interview questions of all technology like java tutorial, android, java frameworks
G-13, 2nd Floor, Sec-3, Noida, UP, 201301, India