0
votes

I'm practicing implementing a Template Class Linked List with the Node struct within the implementation of the Linked List Class. In the createNode() member function, when I initialize a pointer variable to a node struct, I get the compiler error: "Uninitialized local variable 'newNode' used"

I've found if I change the initialization to:

Node* newNode = new Node();

That it works just fine. I'm a bit confused as to why this matters if I can initialize the basic data types like int as:

int* intPtr;

Why can't I do the same with structs?? My code is below:

#include <iostream>
#include <string>

template<class T>
class LinkedList
{
private:
    struct Node
    {
        T data;
        Node* next;
    };
    Node* head;
    Node* tail;
    int size;

public:
    LinkedList() : head{ nullptr }, tail{ nullptr }, size{ 0 }
    {
    }

    Node* createNode(T data)
    {
        Node* newNode;
        newNode->data = data;
        newNode->next = nullptr;

        return newNode;
    }

    void display()
    {
        Node* currentNode = head;

        while (currentNode)
        {
            std::cout << currentNode->data << std::endl;
            currentNode = currentNode->next;
        }
    }

    void push(T data)
    {
        Node* newNode = createNode(data);

        if (size == 0)
        {
            head = newNode;
            tail = newNode;
        }
        else
        {
            tail->next = newNode;
            tail = newNode;
        }

        ++size;
    }
};

int main()
{
    LinkedList<int> list;

    list.push(5);
    list.push(3);
    list.push(6);

    list.display();

    std::cin.clear();
    std::cin.ignore(32767, '\n');
    std::cin.get();

    return 0;
}
1
Have you implemented a non-templated list?user2100815

1 Answers

1
votes

You said:

I'm a bit confused as to why this matters if I can initialize the basic data types like int as:

int* intPtr;

That's a wrong conclusion. If you use:

int* intPtr;
*intPtr = 10;

you'll probably see the same warning/error from the compiler. The correct way to use intPtr will be to make sure it is initialized to point to a valid object before anything is assigned to it using *intPtr.

int* intPtr = new int;
*intPtr = 10;

This is similar to using

Node* newNode = new Node();
newNode->data = data;
newNode->next = nullptr;

in your code.