Tuesday, August 28, 2007

C++ keywords

explicit keyword:
-----------------

In C++ it is possible to declare constructors for a class, taking a single parameter, and use those constructors for doing type conversion.

class CMyClass
{
int a;
public:
CMyClass(int x) :a(x) {}
};

void fun(const CMyClass& a){ cout<<"Implicit Conversion";}

int main(int argc, char* argv[])
{
fun(10); //Implicit Conversion of integer to type CMyClass
return 0;
}

A declaration like:
CMyClass obj = 37;
says to call the CMyClass(int) constructor to create an CMyClass object from the integer value. Such a constructor is called a "converting constructor".

However, this type of implicit conversion can be confusing, and there is a way of disabling it, using a new keyword "explicit" in the constructor declaration:

class CMyClass
{ int a;
public:
explicit CMyClass(int x) :a(x) {}
};

void fun(const CMyClass& a){ cout<<"Implicit Conversion";}

int main(int argc, char* argv[])
{
fun(10); //Error! cannot convert from 'const int' to 'const class CMyClass
fun( CMyClass(10) ); // This works fine.
return 0;
}

No comments: