简体   繁体   中英

C++ object declaration confusion?

I'm trying to implement a BST in C++, and I came across these two ways of creating a node:

node* z = new node();
z->key = d;
z->left = NULL;
z->right = NULL;

and then this:

node* y = NULL;
node* x = root;
node* parent = NULL;

What is the difference in calling the new operator or not?

EDIT

so for example, whats the difference between:

node* q = new node(); 

and

node* q;

and why would you choose one way or the other? Is there an advantage for one way or the other?

To answer the question in the comment, yes there is a difference.

When you do node* q = new node() you declare a pointer to a node object, and then at runtime dynamically allocate memory enough for one node object, and calls the default constructor (alternatively, value initializes the object, it depends on the class/struct), and finally you assign the pointer to the newly allocated object to q .

When you do node* q; you just declare a pointer to a node object, and that's it. What the pointer will be pointing to depends on where you declare the pointer: If you declare it as a global variable, it is initialized to zero, and becomes a null pointer; If you declare it as a local variable its value is indeterminate, and will in reality seem to be random. Neither is a valid pointer, and dereferencing it will lead to undefined behavior . There is also a third alternative, and that's where you declare node* q; as a member variable in a class or struct , then the initial value depend on how the class/structure is created and initialized (for example if the structure is value initialized, if there's a constructor that initializes it, etc.).

I'm pretty sure (Someone correct me if i'm wrong), using the new operator allocates dynamic memory for that variable. The variables will most likely already have some garbage value assigned to them that gets overridden when you assign a new value to them. Whereas assigning it NULL just assigns it whatever the NULL value is (probably 0000000).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM