Help: "explicit" keyword and double parentheses

Hi,
I am just trying to understand “explicit” keyword in C++ and would appreciate some link to gain better understanding.
Also while looking at some online resource, I came across some “not very familiar” notation at this link:
http://cplusplus.com/forum/articles/17108/
==============================================
// constructor
Array2D(unsigned wd,unsigned ht)
:nWd(wd), nHt(ht), pAr(0)
======================XX========================

Could someone explain: nWd(wd), nHt(ht), pAr(0)?

Also, someone else used the following lines few post down:
==============================================
struct Col {
explicit Col( size_t c ) : col( c ) {}
size_t operator()() const { return col; }
private:
size_t col;
};
======================XX========================
what is with this double parentheses … operator()()…?
Thanks in advance,
DK

I am just trying to understand “explicit” keyword in C++

The explicit keyword disallows a constructor from taking part in implicit type conversion.

e.g.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
class Foo
{
     private:
          int member;

     public:
          Foo(int m)
          {
               member = m;
          }
};

Foo f(5); //case 1: the usual class instantiation

Foo f2 = 10; //case 2: 10 is implicitly converted to f2 since Foo has a constructor taking only an int 


If you want to disable the possibility of case 2 above arising in your code, then you must declare the constructor as explicit i.e.:

1
2
3
4
explicit Foo(int m)
{
     member = m;
}


Note that these conversions can only occur if the constructor has only one argument.

Could someone explain: nWd(wd), nHt(ht), pAr(0)?

That is an initializer list. Essentially, :

1
2
3
4
5
6
7
8
9
10
11
12
13
class Foo
{
     private:
          int i;
          bool b;
          char c;

     public:
          Foo(int new_i, bool new_b, char new_c) : i(new_i), b(new_b), c(new_c)
          {
               //constructor body
          }
};


is equivalent to:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
class Foo
{
     private:
          int i;
          bool b;
          char c;

     public:
          Foo(int new_i, bool new_b, char new_c)
          {
               i = new_i;
               b = new_b;
               c = new_c;

               //constructor body
          }
};


You can be sure that the initializer list is executed before the body of the constructor. The actual order of the initialization is not the comma-delimited left-to-right order prescribed in the code, but rather the declaration order of the member variables.

what is with this double parentheses … operator()()…?

That is saying that this operator() is called without parameters.

1
2
3
4
size_t mySize = 5;
Col colInstance(5);

size_t whatSize = colInstance(); //this calls Col::operator()() 
Last edited on
Topic archived. No new replies allowed.