0

My code looks like this:

#include <iostream>

struct Node {
   double data;
   Node* next;
};

int main(){
   Node* a;
   a = new Node;
}

I am having a hard time understanding why the assignment would work for a pointer. Because a is type Node* but the new node is type Node.

At the beginning of my class, I was taught that pointer assignment needs to always be an address.

For example:

int * x;
int y = 5;

This would be allowed:

x = &5;

But this wouldn't:

x = y;

So, by that same logic, shouldn't the assignment of Node* a; be:

a = &(new Node);

Instead of:

a = new Node;

?

Remy Lebeau
  • 555,201
  • 31
  • 458
  • 770

3 Answers3

2

When you call new, it creates a new object and returns a pointer to that object. It is quite common to store that pointer in a pointer variable. You would use & new(...) if it returned a reference to the newly-created object. But it doesn't.

David Schwartz
  • 179,497
  • 17
  • 214
  • 278
  • also, what is the reason for making it "new Node" instead of "new Node()" with the parentheses? thank you for taking your time to answer, I am a student transitioning from Java to C++. – Tim Son Feb 28 '21 at 23:44
  • 1
    @TimSon, There's only a small difference: https://stackoverflow.com/questions/620137/do-the-parentheses-after-the-type-name-make-a-difference-with-new – chris Mar 01 '21 at 00:08
2

but the new Node is type Node.

is absolutely wrong. This is not Java. new Node returns a pointer to a freshly allocated on heap Node.

bipll
  • 11,747
  • 1
  • 18
  • 32
0

First of all, every assignment requires correct type. Either you provide left argument of the exact same type as the variable you assign to, or of a type you can convert from. E.g.

int x = 5; //here x is a type of int and 5 is also an int

or

double w = 3; //here w is a type of double and 3 is again int but int can be converted to double

in contrary

int z = 3.2; //won't compile because 3.2 is a float and floats have to be explicitly casted to ints.

Now, with your code, Node* is a type you read as Node pointer and new allocates memory on heap, creates new object and return its address which in this case is also Node pointer. Types match and everything works.

NRUB
  • 404
  • 4
  • 17
  • "or of a type you can convert from." Are you aware of the fact, that with this, you likely triggered a really complex follow-up confusion about C++ complex conversion rules in doubt? :) – Secundi Mar 01 '21 at 11:12