Sunday, 23 December 2012

When can we use 'explicit' keyword..?


The keyword explicit is used to avoid implicit conversion. In case of implicit conversion we can initialise an object (with one argument) of a class using a constant. This is illustrated in the following program.

class sample
{
private :
int i ;
public :
sample ( int ii )
{
i = ii ;
}
} ;

void fun ( sample s )
{
// code
}

void main( )
{
fun ( 11 ) ; // implicit conversion
}
Here, we have passed integer 11 to fun( ) which would initialize s.i with 11. This is called implicit conversion. We use keyword explicit to avoid this implicit conversion. This keyword is a declaration specifier which can be used only with inline constructors. When a constructor is defined with this keyword, it indicates that the constructor cannot take part in implicit conversion. Thus, explicit conversion forces to initialize an object of a class with an object of the same class. As multiple-argument constructor cannot take part in implicit conversion, explicit can only be used with one-argument constructor. The following program illustrates use of explicit keyword.
class sample
{
private :
int i ;
public :
explicit sample ( int ii )
{
i = ii ;
}
} ;

void fun ( sample s )
{
// code
}

void main( )
{
sample s ( 9 ) ;
fun ( 11 ) ; // error
fun ( s ) ; // explicit conversion
}

No comments:

Post a Comment