0

I am unable to figure out what the problem is in the code below

class Node
{
    private:
        int index, value;

    public:
        Node(int index=0, int value=0):index(index),value(value){}

        int getIndex()
        {
            return index;
        }

        int getValue()
        {
            return value;
        }
};


int main()
{
    Node n = new Node(10,10);
    return 0;
}

I get

invalid conversion from Node* to int

Blaze
  • 16,736
  • 2
  • 25
  • 44
Kraken
  • 23,393
  • 37
  • 102
  • 162

3 Answers3

5

new returns a pointer. You can't assign a pointer to n, it's a Node. The quick fix would be to change the offending line to Node * n = new Node(10,10); or auto n = new Node(10,10);.

However using new is no longer the recommended solution for the dynamic creation of objects in modern c++. Prefer auto n = std::make_unique<Node>(10, 10); instead which makes n a smart pointer. By using smart pointers, you relieve yourself from having to manually track ownership and from having to remember to delete your object exactly once. You also make your code much more robust in case of unexpected exceptions. You'll need to #include <memory>. See std::make_unique and std::make_shared :

#include <memory>

int main()
{
    auto n = std::make_unique<Node>(10,10);
    return 0;
}

Though in this case, it doesn't seem like dynamic allocation is required. Simply using Node n{10, 10}; would be sufficient.

François Andrieux
  • 28,148
  • 6
  • 56
  • 87
2

If you want it on the stack

Node n(10, 10);

The object will be made on the stack. It goes out of scope at the end of the function, or even before it (for instance if it was declared in a loop).

If you want it on the heap

Node *n = new Node(10, 10);

The object is allocated on the heap, and a pointer to it is on the stack. It behaves more you'd expect it with Java's "references". The object will not be deleted when the pointer goes out of scope. Instead, delete has to be called at some point or else the memory will be leaked (unlike with Java's "references", which are garbage collected).

Blaze
  • 16,736
  • 2
  • 25
  • 44
  • 2
    Better yet, use a smart pointer and never call `new` and `delete`. Also always useful to look here: https://stackoverflow.com/q/388242/485343 – rustyx Sep 26 '18 at 14:53
1

When using the new argument you need to use a pointer. The line

Node n = new Node(10,10);

Should be

Node* n = new Node(10,10);

The error message is because the value returned from new is a numeric location in memory and the closest datatype the compiler knows to represent this is an int.

NikNye
  • 119
  • 6
  • A location in memory doesn't look like an int. – rustyx Sep 26 '18 at 14:51
  • 1
    OT: looks like the compiler is trying to create a Node from int using its constructor. Unless you really want `Node n = 5;` to succeed, make the constructor `explicit` –  Sep 26 '18 at 14:51