Explicit in c++

Thursday, January 31, 2013 , 3 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 
}

3 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
  3. But String my( 'y' ) will construct a loooong string anyway, so “explicit” doesn’t solve anything at all here. Why is a = z in any way different from a( z )?

    For this particular example, it’s much better to do it like

    class String {
    public:
    String( char c, size_t n = 1 ); // creates string filled with n chars c
    String( const char* );
    };

    than to try to hide bad design under additional keywords

    ReplyDelete