Hack Forums
[C] Assigning Member Variables in a Constructor - Printable Version

+- Hack Forums (https://hackforums.net)
+-- Forum: Tech (https://hackforums.net/forumdisplay.php?fid=444)
+--- Forum: Coding (https://hackforums.net/forumdisplay.php?fid=151)
+---- Forum: Software Development (https://hackforums.net/forumdisplay.php?fid=118)
+---- Thread: [C] Assigning Member Variables in a Constructor (/showthread.php?tid=6073367)



Assigning Member Variables in a Constructor - Sмℯґƒ - Apr 30, 2020

So I have two string pointers in my class Node, key* and value*, and in my constructor I want to assign them the passed parameters key and value. Am I just being stupid here or what I cannot figure out how to do it.
Currently what I have
Code
RBTree::Node::Node(const string& key, const string& value)
{
  key = key;
  value = value;
}
Here is the Node class which is a nested class for RBTree
Code
class Node {
   public:
      Node(); // use this constructor to create the one nil Node
      Node(const string& key, const string& value);
      ~Node();
      Node *parent;
      Node *left;
      Node *right;
      char color;
      string *key;
      string *value;
   };



RE: Assigning Member Variables in a Constructor - jumprop - Apr 30, 2020

(Apr 30, 2020 05:03 PM)Sмℯґƒ Wrote:  So I have two string pointers in my class Node, key* and value*, and in my constructor I want to assign them the passed parameters key and value. Am I just being stupid here or what I cannot figure out how to do it.
Currently what I have
Code
RBTree::Node::Node(const string& key, const string& value)
{
 key = key;
 value = value;
}
Here is the Node class which is a nested class for RBTree
Code
  class Node {
  public:
     Node(); // use this constructor to create the one nil Node
     Node(const string& key, const string& value);
     ~Node();
     Node *parent;
     Node *left;
     Node *right;
     char color;
     string *key;
     string *value;
  };

I believe there are two changes to this you can use to remedy your problem. The first is to simply change the names of the member variables so that they don't match exactly the names of your second constructor method's arguments. The ambiguity this introduces will confuse both the reader of your code and the compiler's ability to figure out which 'key' and 'value' you're referring to in your statement. The second is to use 'this->key = key;' and 'this->value = value;' in place of the two assignment statements you currently have in your constructor. Please correct me if anything I say is incorrect.


RE: Assigning Member Variables in a Constructor - 0xDEAD10CC - May 1, 2020

The assignment from const ref to pointer doesn't make any sense. There is an obvious third option once you correct the first problem, and that is to use an initializer list..

Code
RBTree::Node::Node(const string& key, const string& value)
    : key(key), value(value)
{ }

With the same names though, member shadowing is occurring.