Home Upgrade Search Memberlist Extras Hacker Tools Award Goals Help Wiki Contact

C 

Assigning Member Variables in a Constructor

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;
   };
[Image: hfnmhEI.jpg]
(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.
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.
Getting Started: C/C++
[C/C++/.NET/x86 ASM - Automation Programmer]


Possibly Related Threads...
Thread / Author Replies Views Last Post
[Javascript]  by Z3R00NDATOct 16, 2023 01:24 PM 3 133 Oct 16, 2023 01:24 PM
Last Post: Disease
[C] by bhaktefhabo87Oct 11, 2021 07:28 AM 2 180 Oct 11, 2021 07:28 AM
Last Post: Cool_Pro_Grammer
[Python] by simmerMay 28, 2021 05:33 AM 5 200 May 28, 2021 05:33 AM
Last Post: simmer