Thursday, January 31, 2013

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 
}
Categories: ,

0 comments:

Post a Comment