Explicit in c++

Thursday, January 31, 2013 , 1 Comments

Many a times we wonder why this explicit keyword is used when ever we came across any c++ code. Here I would like to give a simple explanation of this keyword which can be more convincing to all.
Suppose you have a class String
class String {
String (int n);//allocate n bytes to the String object 
String(const char *p); // initializes object with char *p 
Now if you try
String mystring='x';
The char 'x' will be converted to int and will call String(int) constructor. But this is not what the user might have intended. So to prevent such conditions, we can define the class's constructor as explicit.
class String {
explicit String (int n); //allocate n bytes
String(const char *p); // initialize sobject with string p 

1 comment:

  1. "The char 'x' will be converted to int" this line is not correct as char is basically an int !!!