-8
class sortedList
{
    class Node
    {
        public:
            int value;
            Node* next;

            Node()
            {
                this->value = 0;
                this->next = NULL;
            }
            Node(int value)
            {
                this->value = value;
                this->next = NULL;
            } 
    }* head = NULL, * tail = NULL;

    public:
        void addNode(int value)
        {
            Node* n = Node(value);
            //More code...
        }
};

Why does adding new before Node(value) make the code correct? I think the code above should stay wrong because pointer doesn't equal a node.

  • 3
    `=` means assignment, not comparison. – Evg Nov 11 '19 at 16:35
  • adding the `new` makes it more like `(new Node)(value)`, not `new (Node(value))` like you seem to think. It's a completely different expression, not a unary operand applied to the same sub-expression. –  Nov 11 '19 at 16:35
  • 4
    `Node(value)` returns a `Node`, but `new Node(value)` returns a pointer to a `Node`. – HolyBlackCat Nov 11 '19 at 16:35
  • [Prefer](https://arne-mertz.de/2015/12/modern-c-features-nullptr/) `nullptr` to `NULL`.. – Håkon Hægland Nov 11 '19 at 16:53

2 Answers2

4

Node(value) is a temporary value of type Node. Node* n is a variable of type Node*. You're attempting to initialise an object of type Node* with an argument of type Node. These types are not implicitly convertible to one another, so the program is ill-formed.

The result of new T is T*. So, result of new Node(value) is a Node*. An object of type Node* can be initialised with an argument of type Node*.

eerorika
  • 232,697
  • 12
  • 197
  • 326
3

This is not valid code:

Node* n = Node(value);

The reason new makes it work is that new returns a pointer.

You can either declare your Node using dynamic storage:

Node* n = new Node(value);

or automatic storage:

Node n(value);
Cory Kramer
  • 114,268
  • 16
  • 167
  • 218