Signup/Sign In
Ask Question
Not satisfied by the Answer? Still looking for a better solution?

What does the explicit keyword mean in C++ Language ?

What does the explicit keyword mean in C++?
by

2 Answers

Bharatgxwzm
Assume, you have a class String:
class String {
public:
String(int n); // allocate n bytes to the String object
String(const char p); // initializes object with char *p
};

Then, if you try:
String mystring = 'x';

The character 'x' will be verifiably changed over to int and afterwards the String(int) constructor will be called. Yet, this isn't what the client may have planned. Thus, to forestall such conditions, we will characterize the constructor as explicit:
class String {
public:
explicit String (int n); //allocate n bytes
String(const char
p); // initialize so bject with string p
};
Sonali7
The explicit function specifier controls unwanted implicit type conversions. Basically, it tells the compiler that only explicit call to this constructor is allowed.
For example, if there is a buffer class whose constructor Buffer(int size) takes the size of the buffer in bytes, and you don't want the compiler to quietly turn int s into Buffers. So to prevent that, you declare the constructor with the explicit keyword:
class Buffer 
{
explicit Buffer(int size);
...
}


That way,
void useBuffer(Buffer& buf);
useBuffer(4);

becomes a compile-time error. If you want to pass a temporary Buffer object, then do the following
useBuffer(Buffer(4));

This will prevent the compiler from surprising you with unexpected conversions.

Login / Signup to Answer the Question.