Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Why I can't assign variables with constructor and get the wrong value from it?

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading