Have problem with constructor.

Hi everybody.
Please explain me why second constructor (Map(char * key, double val))
doesn't works. If you can please correct it.


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
class Map
{
private:
struct tree_node
{
tree_node* left;
tree_node* right;
double data;
char * key;
};

tree_node* root;
		    
public:
Map()
{
root = NULL;
}

Map(char * key, double val)
{
root->key = key;
root->data = val;
root->left = NULL;
root->right = NULL;
}
};


The exprassion like
Map Salary("akmal4ik",1);
Doesn't work.
Last edited on
Three things.

1) root is uninitialized so you are accessing random memory.
2) you probably want a "deep" copy of the key, not just a copy of the pointer.
3) you probably want to pass key as a const char*.

1
2
3
4
5
6
7
8
9
10
class Map {
  // ...
  Map( const char* key, double val )  // Pass by const char*
  {
      root = new tree_node;           // Initialize the root pointer before using
      root->key = strdup( key );      // "Deep" copy of the string, not just a pointer copy
      root->data = val;
      root->left = root->right = 0;
  }
};


You will then need to ensure that tree_node::key gets destroyed so the memory
is freed. Here is one way:

1
2
3
4
5
6
struct tree_node {
   // ...
   ~tree_node() {
        delete key;
   }
};


I have several other "best practice" comments, but I'll refrain unless you want me
to post them.
Last edited on
Duplicate thread.
Question answered here: http://www.cplusplus.com/forum/general/3509/
Topic archived. No new replies allowed.