Search code examples
c++memory-managementnew-operator

Invalid conversion from class pointer to int


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


Solution

  • 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.