0

I would like to implement a BST in C++, but I found that the integer variable "val" I pass in the constructor "Node()" seem not to work properly. P.S. I am a totally newbie to this language, and here is my code

#include<iostream>
using namespace std;


class Node{

    public:
        int val;
        Node *left;
        Node *right;
        // the constructor
        Node(int val){
            val = val;
            left = nullptr;
            right = nullptr;
        }
};

class BST{
    public:
        Node *root;
        BST(){
            root = nullptr;
        }
        void insert(int val);
};

void BST::insert(int val){
    if (root == nullptr){
        root = new Node(val);
        cout << root->val << endl; // output: 40580256(this number changes every time I run the code) 
        delete root;
    };
    
    if (root->val == val){
        cout<<"The value: " << val << " is duplicated!" << endl;
    }

}

int main() {
    BST bst;
    Node a = Node(10); // output: 8
    cout << a.val << endl;;
    bst.insert(8);
    
    
    return 0;
}

It only works when I directly assign the variable "val" to root.val instead of using constructor to assign.

Cody Gao
  • 3
  • 3
  • 3
    `val = val;` is your problem. What do you think that line does? Can you [explain to your rubber duck](https://en.wikipedia.org/wiki/Rubber_duck_debugging) what that line does? – Drew Dormann May 09 '23 at 14:19
  • You probably meant `this->val = val;` – Aykhan Hagverdili May 09 '23 at 14:21
  • Put another way, how do you think that the compiler can tell whether `val` refers to the parameter `val` or the member variable `val`? Obviously it cannot read your mind and know what you intended. – john May 09 '23 at 14:44
  • Thank you guys so much, now I change the parameter name from "val" into "value" and it works properly. Also another solution to use "this" operator works as well! Love the strong community : ) – Cody Gao May 09 '23 at 14:50

1 Answers1

1

The reason why you're having a problem is outlined in the comments, but, stylistically, it's better to do this:

class Node{

    public:
        int val;
        Node *left = nullptr;
        Node *right = nullptr;
        // the constructor
        Node(int val) : val (val) { }
};

Now, nothing can go wrong.

Paul Sanders
  • 24,133
  • 4
  • 26
  • 48