Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the explicit keyword for in c++? [duplicate]

Tags:

c++

syntax

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?

like image 998
user198729 Avatar asked Jul 18 '10 13:07

user198729


2 Answers

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
like image 75
tpdi Avatar answered Sep 24 '22 05:09

tpdi


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.

like image 34
In silico Avatar answered Sep 23 '22 05:09

In silico