Why we use "Explicit" keyword in C++ ?

0 votes
asked in Interview Question by nitin2604

What is the use of “Explicit” keyword. What exactly it does in compile time?

Add question to:

1 Answer

+1 vote
answered by nitin2604
selected by nitin2604
 
Best answer

The “Explicit” keyword is in C++. Before going in depth of explicit keyword let’s see some default features that class have.

Default Functions in C++ class

In C++03

  1. Default Constructor
  2. Copy Constructor
  3. Copy assignment operator
  4. Destructor

But C++11 have the two more function

  1. Move Constructor
  2. Move assignment operator.

If a user does not define/declare these functions, they are always present and does the implicit type conversion. Default constructor does not have any argument whereas move and copy constructor’s parameter are already present there with its class type.

So, when we are using the explicit keyword, it will control all implicit type of conversions, and it would be illegal to use the other implicit constructor. It will give a compilation error. 

See, the below example

class WayToCrack
{  public:
   WayToCrack();
   WayToCrack(int);
   WayToCrack(const char*, int = 0);
};
int main(){
WayToCrack A = 1;
WayToCrack B = "xyz";
}

When the first object is made “WayToCrack A = 1”, this will be similar to “WayToCrack A = WayToCrack (1)”.  The compiler does this conversion implicitly. 

When the user uses “Explicit” keyword :

See, the below example

class WayToCrack
{  public:
   explicit  WayToCrack();
   explicit  WayToCrack(int);
   explicit  WayToCrack(const char*, int = 0);
};
int main(){
WayToCrack A = 1; // illegal access
WayToCrack B = "xyz"; //// illegal access
}

This type of object creation will be illegal because now compiler will not allow implicit type conversion. So it will show compile time error.

To get rid to this, user has to use another type of method to create object or go explicit type conversion as shown in below example in 2nd object creation “WayToCrack B = WayToCrack(1) //Legal”

class WayToCrack
{  public:
   explicit  WayToCrack();
   explicit  WayToCrack(int);
   explicit  WayToCrack(const char*, int = 0);
};
int main(){
WayToCrack A(1); // Legal 
WayToCrack B = WayToCrack(1) //Legal
}

 

...