0

I am a bit confused by the following constructor. I understand that the values key, value and next are being initialized here but the parenthesis following them throw me off. Is the action key(key) passing a type K object to type K constructor? What is going on here? The webpage I am looking at is here. Any help is much appreciated.

// Hash node class template
template <typename K, typename V>
class HashNode
{
public:

    HashNode(const K &key, const V &value)
        : key(key), value(value)
    {}

private:

    // key-value pair
    K key;
    V value;
};
Captain Obvlious
  • 19,754
  • 5
  • 44
  • 74
Rhurac
  • 439
  • 4
  • 16
  • @NickyC That one is about in-class member initializers, not the member initializer list. – Emil Laine Dec 09 '15 at 01:41
  • Additional reading: [Why should I prefer to use member initialization list?](http://stackoverflow.com/questions/926752/why-should-i-prefer-to-use-member-initialization-list) – user4581301 Dec 09 '15 at 01:43
  • All right thanks everyone. Now that I have the right term , "member initializer" to google this is great I couldn't think of how to search for this answer – Rhurac Dec 09 '15 at 01:44
  • That's the way it is, sadly. Can't google smurf if you don't know smurf, and the Member Initializer List is one of the most under-taught important concepts in C++. Can't do a complex base class or member object without one. – user4581301 Dec 09 '15 at 01:51

3 Answers3

7

: key(key) just means to initialize the private member 'key' with the value from the argument 'key'. Even having the same name it's not ambiguous because only members can be initialized using this syntax, whereas the rules C++ uses for resolving symbol names means that locally-defined (including via the argument list) names are examined first, so the second 'key' must refer to the argument. Whether this is good practice is a matter of taste perhaps.

Dylan Nicholson
  • 1,235
  • 14
  • 20
2

In C++, all members are initialized before the main body of the constructor is called (if a member is left out it is initialized with the appropriate default constructor). The general syntax is foo(bar), where foo is the name of the member to be initialized, and bar> is the value you are initializing it to.

In this particular instance, you have key(key). The first instance of key is the name of the member, and the second instance is the value it is being initialized with. The value here refers to the const reference you passed in by the same name. I believe your confusion has to do with the fact that the same names are used.

Andy Soffer
  • 173
  • 7
2

The part of the constructor you are asking about is documented here: http://en.cppreference.com/w/cpp/language/initializer_list

It is called a member initializer list.

Kevin Tindall
  • 375
  • 5
  • 16