T& operator[] (const int index); Warning

  c++, linked-list

I am trying to resolve a little problem. So I’m studying Linked List and when I code this prototype

T& operator[] (const int index); and then compiling it in code this warning appears:

warning: non-void function does not return a value
      in all control paths [-Wreturn-type]

note: in instantiation of member function 'List<int>::operator[]' requested here
    std::cout << "Выводим элемент (на данный момент [0]) обычным cout: " << list[0] << std::endl;

I understand that this function is not void and it should return a value but in tutorial that I was watching he has same code but has no warning.

template<class T>
T& List<T>::operator[] (const int index)
{
    int count = 0;
    Node<T> * current = this->head;

    while (current != nullptr)
    {
        if (count == index)
        {
            return current->data;
        }
        current = current->p_next;
        count++;
   }
}

And this is full code:

#include <iostream>
#include <ctime>

template<class T>
class List
{
    template<class T1>
    struct Node
    {
        T data;
        Node * p_next;
        Node(T data = T(), Node * p_next = nullptr): data(data), p_next(p_next) {};
    };

    int size;
    Node <T> * head;

public:
    List();
    void push_back(T data);
    int get_size() { return size; };
    T& operator[] (const int index);
};

template<class T>
List<T>::List()
{
    size = 0;
    head = nullptr;
}

template<class T>
void List<T>::push_back(T data)
{
    if (head == nullptr)
    {
        head = new Node<T>(data);
    }
    else
    {
        Node<T> * current = this->head;

        while (current->p_next != nullptr)
        {
            current = current->p_next;
        }
        current->p_next = new Node<T>(data);
    }
    size++;
}

template<class T>
T& List<T>::operator[] (const int index)
{
    int count = 0;
    Node<T> * current = this->head;

    while (current != nullptr)
    {
        if (count == index)
        {
            return current->data;
        }
        current = current->p_next;
        count++;
    }
}



int main()
{
    srand(time(nullptr));

    List<int> list;
    int numbers_count;
    std::cout << "Сколько индексов создать? ";
    std::cin >> numbers_count;

    for (int i = 0; i < numbers_count; i++)
    {
        list.push_back(rand() % 10);
    }

    std::cout << "Выводим элемент (на данный момент [0]) обычным cout: " << list[0] << std::endl;

    std::cout << "Либо циклом for: n";
    for (int i = 0; i < list.get_size(); i++)
    {
        std::cout << list[i] << std::endl;
    }

    std::cout << "Количество элементов: " << list.get_size() << std::endl;
    return 0;
}

Source: Windows Questions C++

LEAVE A COMMENT