tags:

views:

100

answers:

2

Possible Duplicate:
What does the explicit keyword in C++ mean?

explicit CImg(const char *const filename):_width(0),_height(0),_depth(0),_spectrum(0),_is_shared(false),_data(0) {
  assign(filename);
}

what's the difference with or without it?

+5  A: 

The explicit keyword prevents implicit conversions.

// Does not compile - an implicit conversion from const char* to CImg
CImg image = "C:/file.jpg"; // (1)
// Does compile
CImg image("C:/file.jpg"); // (2)

void PrintImage(const CImg& img) { };

PrintImage("C:/file.jpg"); // Does not compile (3)
PrintImage(CImg("C:/file.jpg")); // Does compile (4)

Without the explicit keyword, statements (1) and (3) would compile because the compiler can see that a const char* can be implicitly converted to a CImg (via the constructor accepting a const char*). Sometimes this implicit conversion is undesirable because it doesn't always make sense.

In silico
+2  A: 

It's use to decorate constructors; a constructor so decorated cannot be used by the compiler for implicit conversions.

C++ allows up to one user-provided conversion, where "user-provided" means, "by means of a class constructor", e.g., in :

 class circle {
   circle( const int r ) ;
 }

  circle c = 3 ; // implicit conversion using ctor

the compiler will call the circle ctor here, constructinmg circle c with a value of 3 for r.

explicit is used when you don't want this. Adding explicit means that you'd have to explicitly construct:

 class circle {
   explicit circle( const int r ) ;
 }

  // circle c = 3 ; implicit conversion not available now
  circle c(3); // explicit and allowed
tpdi