Search code examples
c++structinitializer

Initialize values of a struct pointer


I am starting to learn binary trees in cpp and dynamically allocated memories; thus to initialize a struct I do this

struct node{
    int val;
    node* left;
    node* right;
};
//Initialize:
node* root = new node;
root->val = 7;
root->left = NULL;
root->right = NULL;

I would like to know if there is a better way to set the struct values without writing the last three lines of code. I saw on some web pages that they do this:

int* n = new int(6);

Thanks!


Solution

  • You can write a custom constructor:

    struct node{
        int val;
        node* left;
        node* right;
        node(int);
    };
    
    node::node(int _v){
        this->val = _v;
        this->left = this->right = nullptr;
    }
    
    node *root = new node(6); // Works as you want
    

    Or use member initializer list, which looks simpler:

    struct node{
        int val;
        node* left;
        node* right;
        node(int _v) : val(_v), left(nullptr), right(nullptr) {};
    };
    

    Don't forget the braces after the list.