Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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!

like image 869
polmonroig Avatar asked Jan 22 '18 14:01

polmonroig


2 Answers

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.

like image 74
iBug Avatar answered Oct 06 '22 16:10

iBug


In addition to iBug's answer about using a constructor, if your object is a Plain Old Data type you can use aggregate initialisation to construct it using an initialiser-list, in the following manner, which avoids needing to define your own constructor at all:

node root = {7, nullptr, nullptr};

Or if you're allocating on the heap as you are doing:

node* root = new node{7, nullptr, nullptr};

You can have a look at this page on aggregate initialization for more information.

like image 5
Sean Burton Avatar answered Oct 06 '22 16:10

Sean Burton