The Wayback Machine - https://web.archive.org/web/20240717033835/https://www.geeksforgeeks.org/use-of-explicit-keyword-in-cpp/
Open In App

Use of explicit keyword in C++

Last Updated : 14 Sep, 2022
Improve
Suggest changes
Post a comment
Like Article
Like
Save
Share
Report

Explicit Keyword in C++ is used to mark constructors to not implicitly convert types in C++. It is optional for constructors that take exactly one argument and work on constructors(with a single argument) since those are the only constructors that can be used in typecasting.

Let’s understand explicit keyword through an example. 

Predict the output of the following C++ Program

CPP




// C++ program to illustrate default
// constructor without 'explicit'
// keyword
#include <iostream>
using namespace std;
 
class Complex {
private:
    double real;
    double imag;
 
public:
   
    // Parameterized constructor
    Complex(double r = 0.0,
            double i = 0.0) : real(r),
                              imag(i)
    {
    }
 
    // A method to compare two
    // Complex numbers
    bool operator == (Complex rhs)
    {
        return (real == rhs.real &&
                imag == rhs.imag);
    }
};
 
// Driver Code
int main()
{
    // a Complex object
    Complex com1(3.0, 0.0);
 
    if (com1 == 3.0)
        cout << "Same";
    else
        cout << "Not Same";
    return 0;
}


Output

Same

As discussed in this article, in C++, if a class has a constructor which can be called with a single argument, then this constructor becomes a conversion constructor because such a constructor allows conversion of the single argument to the class being constructed. In this case, when com1 == 3.0 is called, 3.0 is implicitly converted to Complex type because the default constructor can be called with only 1 argument because both parameters are default arguments and we can choose not to provide them.
We can avoid such implicit conversions as these may lead to unexpected results. We can make the constructor explicit with the help of an explicit keyword. For example, if we try the following program that uses explicit keywords with a constructor, we get a compilation error.

CPP




// C++ program to illustrate
// default constructor with
// 'explicit' keyword
#include <iostream>
using namespace std;
 
class Complex {
private:
    double real;
    double imag;
 
public:
    // Default constructor
    explicit Complex(double r = 0.0,
                     double i = 0.0) :
                     real(r), imag(i)
    {
    }
 
    // A method to compare two
    // Complex numbers
    bool operator == (Complex rhs)
    {
        return (real == rhs.real &&
                imag == rhs.imag);
    }
};
 
// Driver Code
int main()
{
    // a Complex object
    Complex com1(3.0, 0.0);
 
    if (com1 == 3.0)
        cout << "Same";
    else
        cout << "Not Same";
    return 0;
}


Output

Compiler Error : no match for 'operator==' in 'com1 == 3.0e+0'

We receive an error here because to avoid any unexpected errors we have made our constructor an explicit constructor and 3.0 won’t be converted to Complex by our constructor on its own.

We can still typecast the double values to Complex, but now we have to explicitly typecast it. For example, the following program works fine.

CPP




// C++ program to illustrate
// default constructor with
// 'explicit' keyword
#include <iostream>
using namespace std;
 
class Complex {
private:
    double real;
    double imag;
 
public:
   
    // Default constructor
    explicit Complex(double r = 0.0,
                     double i = 0.0):
                     real(r) , imag(i)
    {
    }
 
    // A method to compare two
    // Complex numbers
    bool operator == (Complex rhs)
    {
        return (real == rhs.real &&
                imag == rhs.imag);
    }
};
 
// Driver Code
int main()
{
    // a Complex object
    Complex com1(3.0, 0.0);
 
    if (com1 == (Complex)3.0)
        cout << "Same";
    else
        cout << "Not Same";
    return 0;
}


Output

Same

Note: The explicit specifier can be used with a constant expression. However, if that constant expression evaluates to true, then only the function is explicit.



Similar Reads

extern Keyword in C
extern keyword in C applies to C variables (data objects) and C functions. Basically, the extern keyword extends the visibility of the C variables and C functions. That's probably the reason why it was named extern. Though most people probably understand the difference between the "declaration" and the "definition" of a variable or function, for th
7 min read
Comparison of static keyword in C++ and Java
Static keyword is used for almost the same purpose in both C++ and Java. There are some differences though. This post covers similarities and differences of static keyword in C++ and Java. Similarities between C++ and Java for Static KeywordStatic data members can be defined in both languages.Static member functions can be defined in both languages
6 min read
C++ | Static Keyword | Question 1
Predict the output of following C++ program. #include &lt;iostream&gt; using namespace std; class Test { static int x; public: Test() { x++; } static int getX() {return x;} }; int Test::x = 0; int main() { cout &lt;&lt; Test::getX() &lt;&lt; &quot; &quot;; Test t[5]; cout &lt;&lt; Test::getX(); } (A) 0 0 (B) 5 5 (C) 0 5 (D) Compiler Error Answer: (
1 min read
C++ | Static Keyword | Question 2
#include &lt;iostream&gt; using namespace std; class Player { private: int id; static int next_id; public: int getID() { return id; } Player() { id = next_id++; } }; int Player::next_id = 1; int main() { Player p1; Player p2; Player p3; cout &lt;&lt; p1.getID() &lt;&lt; &quot; &quot;; cout &lt;&lt; p2.getID() &lt;&lt; &quot; &quot;; cout &lt;&lt; p
1 min read
C++ | friend keyword | Question 1
Predict the output of following program. #include &lt;iostream&gt; using namespace std; class A { protected: int x; public: A() {x = 0;} friend void show(); }; class B: public A { public: B() : y (0) {} private: int y; }; void show() { A a; B b; cout &lt;&lt; &quot;The default value of A::x = &quot; &lt;&lt; a.x &lt;&lt; &quot; &quot;; cout &lt;
1 min read
C++ | friend keyword | Question 2
Predict the output the of following program. #include &lt;iostream&gt; using namespace std; class B; class A { int a; public: A():a(0) { } void show(A&amp; x, B&amp; y); }; class B { private: int b; public: B():b(0) { } friend void A::show(A&amp; x, B&amp; y); }; void A::show(A&amp; x, B&amp; y) { x.a = 10; cout &lt;&lt; &quot;A::a=&quot; &lt;&lt;
1 min read
C++ | Static Keyword | Question 4
Predict the output of following C++ program. #include &lt;iostream&gt; using namespace std; class A { private: int x; public: A(int _x) { x = _x; } int get() { return x; } }; class B { static A a; public: static int get() { return a.get(); } }; int main(void) { B b; cout &lt;&lt; b.get(); return 0; } (A) 0 (B) Linker Error: Undefined reference B::a
1 min read
C++ | const keyword | Question 1
Predict the output of following program #include &lt;iostream&gt; using namespace std; int main() { const char* p = &quot;12345&quot;; const char **q = &amp;p; *q = &quot;abcde&quot;; const char *s = ++p; p = &quot;XYZWVU&quot;; cout &lt;&lt; *++s; return 0; } (A) Compiler Error (B) c (C) b (D) Garbage Value Answer: (B) Explanation: Output is ‘c’ c
1 min read
C++ | const keyword | Question 2
In C++, const qualifier can be applied to 1) Member functions of a class 2) Function arguments 3) To a class data member which is declared as static 4) Reference variables (A) Only 1, 2 and 3 (B) Only 1, 2 and 4 (C) All (D) Only 1, 3 and 4 Answer: (C) Explanation: When a function is declared as const, it cannot modify data members of its class. Whe
1 min read
C++ | const keyword | Question 3
Predict the output of following program. #include &lt;iostream&gt; using namespace std; class Point { int x, y; public: Point(int i = 0, int j =0) { x = i; y = j; } int getX() const { return x; } int getY() {return y;} }; int main() { const Point t; cout &lt;&lt; t.getX() &lt;&lt; &quot; &quot;; cout &lt;&lt; t.getY(); return 0; } (A) Garbage Value
1 min read
Article Tags :
Practice Tags :
three90RightbarBannerImg