Explicit in c++

Thursday, January 31, 2013 , 2 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 {
public: 
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 {
public: 
explicit String (int n); //allocate n bytes
String(const char *p); // initialize sobject with string p 
}

2 comments:

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

    ReplyDelete
  2. a char is not an int and an int is not a char. a char can be converted to the decimal equivalent but the conversion doesn't make a char an int or an int a char so you are wrong Prashant.

    ReplyDelete