7

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!

polmonroig
  • 937
  • 4
  • 12
  • 22
  • yes thats called a constructor http://www.learncpp.com/cpp-tutorial/85-constructors/ – aram Jan 22 '18 at 14:21

2 Answers2

8

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.

iBug
  • 35,554
  • 7
  • 89
  • 134
  • Have I been learning the wrong C++ all my life? This is the first I have heard of a custom constructor or a member initializer list for a struct. – lanxion Sep 04 '20 at 21:48
6

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.

Sean Burton
  • 907
  • 7
  • 15
  • Yes, that works too, I'll keep it in mind, tank you, but in the case I am currently working I prefer the constructor. – polmonroig Jan 22 '18 at 17:26
  • What happens if your struct holds 3 pointers, but you construct it with the initializer list with only two arguments? Will it be NULL? Can I define a default value? – Qwert Yuiop Oct 16 '22 at 12:52