Xerunix
Xerunix

Reputation: 431

C++ Basic template class constructor

I am confused about the object creation concerning the data members of the BSTNode class. For example, in the header file one of the data members is defined as "Key k". Does this mean that the default key has already been created and I don't need to write anything in the default BSTNode constructor or do I still need to write Key k; in the constructor to create the default key? Does this still hold true when I am passing a Key to set as k in the constructor?

Class definition (in header):

 class BSTNode {
 public:
   BSTNode();
   BSTNode(Key k, Value v);

   Key k;
   Value v;
   BSTNode* left;
   BSTNode* right;
};

This is my attempt:

template <class Key, class Value>
BSTNode<Key,Value>::BSTNode(){
    Key kk; //create th default key
    k = kk; //set the BSTNode's k to the default key
    Value vv; //create the default value
    v = vv; //set the BSTNode's v to the default value
    BSTNode* left = NULL; //set left pointer to NULL
    BSTNode* right = NULL; //set right pointer to NULL
 }

Upvotes: 1

Views: 190

Answers (1)

PaulMcKenzie
PaulMcKenzie

Reputation: 35440

Your constructor is basically a no-op.

Let's go through each line:

template <class Key, class Value>
BSTNode<Key,Value>::BSTNode(){
    Key k;     // <--- local variable, destroyed on return
    Value v;   // <--- local variable, destroyed on return
    BSTNode* left = NULL;  // <--- local variable initialized to NULL, destroyed on return
    BSTNode* right = NULL; // <--- local variable initialized to NULL, destroyed on return
}

You are not initializing class member variables -- what you're doing is creating brand new, local variables, and setting them to a value. Once the constructor completes, those local variables no longer exist.

What you want to do is this:

class BSTNode {
 public:
   BSTNode();
   BSTNode(Key theKey, Value theValue) : 
   Key m_key;
   Value m_value;
   BSTNode* m_left;
   BSTNode* m_right;
};

 template <class Key, class Value>
    BSTNode<Key,Value>::BSTNode() : 
            m_key(Key()), m_value(Value()), m_left(0), m_right(0) {}

 template <class Key, class Value>
     BSTNode(Key theKey, Value theValue) : m_key(theKey), m_value(theValue), m_left(0), m_right(0) 
     {
        //...
     }

Note that the 0-argument version of the constructor initializes the key and value to whatever the default initial values are of the Key and Value types.

Upvotes: 4

Related Questions