Explicit in C++
What is explicit in C++?
In C++, the explicit keyword is used with a constructor to stop it from doing implicit conversions by specifying the explicit keyword. This keyword is intended to prevent a few implicit conversions when a class contains a single-argument constructor, which the compiler typically interprets as an implicit conversion constructor. That could result in some unwanted outputs, so to prevent those outcomes, we must define such constructors with an explicit keyword before the constructor’s name. Explicit constructors are typically defined when we cannot employ implicit constructors, and they always have one or more parameters.
Explicit keyword Working in C++
In C++, constructors are special methods. They are called automatically whenever we have to create an object of a class. Constructors, which the compiler automatically supplies, are mostly used for initializing or constructing class objects. We can use these constructors for type conversions, like explicit or implicit conversions, within the class declaration. Such constructors are used in typecasting, although this explicit keyword is optional and always accepts only one parameter.
If the implicit conversions are not manageable, we must declare this constructor using the explicit keyword declaration for the constructors within the class declaration. However, we must remember that we cannot use this explicit keyword for the default constructor.
Example for the explicit keyword in C++
In the example below, we will examine implicit conversion and how to prevent it using the C++ explicit keyword.
We create a class Example. An integer is supplied to the Example constructor, which then assigns it to example1. This integer's value is returned by the get Example() method. Additionally, we build a method outside of this class that accepts as a parameter an object from the Example class and displays the result of the member function getExample() on that object.
Code
#include <iostream>
using namespace std;
class Example{
public:
Example(int n){
example1 = n;
}
int getExample(){
return example1;
}
private:
int example1;
};
void getExampleExternally(Example example){
cout << example.getExample();
}
// Driver Code
int main()
{
getExampleExternally(10);
return 0;
}
Output
![Explicit in C++](https://static.tutorialandexample.com/cpp/explicit-in-cpp1.png)
Explanation
We can see that a parameter of type Example object is accepted by the getExampleExternally function. However, if we use our driver code to send an integer to it, it continues to function properly. That is because the compiler implicitly transformed the integer into the Example class. After all, the constructor of the Example class accepts an integer. As a result, our program is effective.
Let's now look at how the explicit constructor in C++ can prevent the above-mentioned implicit conversion.
We place the C++ explicit keyword before the constructor to do this.
Code:
#include <iostream>
using namespace std;
class Example{
public:
explicit Example(int n){
example1 = n;
}
int getExample(){
return example1;
}
private:
int example1;
};
void getExampleExternally(Example example){
cout << example.getExample();
}
// Driver Code
int main()
{
getExampleExternally(10);
return 0;
}
Output
![Explicit in C++](https://static.tutorialandexample.com/cpp/explicit-in-cpp2.png)
Explanation
We instruct the class not to do any implicit operations using the C++ explicit keyword before the constructor. As a result, the type Demo class is no longer transformed to the integer 10. The compiler will throw an error as a result of this.
Example code 2
#include <iostream>
using namespace std;
class Example2
{
private:
int i;
int j;
public:
Example2 (int m = 0, int s = 0): i(m), j(s) {}
bool operator == (Example2 e) {
return (i == e.i && j == e.j)? false: true;
}
};
int main()
{
Example2 ins(6,8);
cout << "It will print matched if the given values matches else not same which uses implicit call to convert int to Example2 type:" <<endl;
cout<< "\n" <<endl;
if (ins == 6)
cout << "matched";
else
cout << "Not matched";
return 0;
}
Output
![Explicit in C++](https://static.tutorialandexample.com/cpp/explicit-in-cpp3.png)
Explanation
In the program mentioned above, the constructor uses two arguments. When there is only one argument constructor, it is typically best practice to use it explicitly since invoking two or more argument constructors in the main function could be confusing. Therefore, the constructor is called implicitly by the compiler in the instance mentioned above, even though there are other proper and legal ways to obtain the output.
It is conceptually incorrect to convert the types, so we use the explicit keyword for the constructor to avoid the unwanted execution of programs that may give outputs. In the above code, we can rewrite the code with an explicit keyword before the constructor declaration within the class, such as "explicit Example2(int a = 0, int b = 0): i(a), j(b) {}". The use of the explicit keyword will raise an error during compilation.
Code
#include <iostream>
using namespace std;
class Example2
{
private:
int i;
int j;
public:
explicit Example2 (int m = 0, int s = 0): i(m), j(s) {}
bool operator == (Example2 e) {
return (i == e.i && j == e.j)? false: true;
}
};
int main()
{
Example2 ins(6,8);
cout << "It will print matched if the given values matches else not same which uses implicit call to convert int to Example2 type:" <<endl;
cout<< "\n" <<endl;
if (ins == 6)
cout << "matched";
else
cout << "Not matched";
return 0;
}
Output
![Explicit in C++](https://static.tutorialandexample.com/cpp/explicit-in-cpp4.png)
Uses of explicit in C++
The explicit keyword indicates to constructors that they should not transform types implicitly in C++. Given that the only constructors that can be used in typecasting are those that accept exactly one parameter and operate on constructors (with a single argument), it is optional for them.
Conclusion
In C++, the explicit keyword is typically used for constructors that produce class objects within the class declaration. The explicit keyword is only used for constructors when we want to prevent the implicit calls made by the compilers. Whenever you find an error stating “a non-scalar type is present” occurs, it is always recommended to use an explicit keyword.