template class help

How do I make this work? It works for integers correctly but I don't know what to do when passing a string. I don't want the complete implementation of the list so don't give me that thanks. I just want to get this current code working and then I will go off from there.


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
#include <iostream>

using namespace std;

template <class T>
class List{

private:

    struct Node{
        T data;
        Node * next;
    };

    Node * head;
    Node * current;

public:

    List();
    //~List();
    T insert(T val);
    void print();

};

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

template <class T>
T List<T>::insert(T val)
{
    Node * n = new Node;
    n->data = val;
    n->next = nullptr;

    if(head == nullptr)
    {
        head = n;
    }
}

template <class T>
void List<T>::print()
{
    cout << head->data;
}

int main()
{
    List<string> one;
    one.insert("red");

}
Last edited on
What's your problem, it works just fine here
Last edited on
really? On my end it just seems to crash for an unknown reason. I'm using codeblocks as my IDE if it matters.

||=== Build: Debug in Review (compiler: GNU GCC Compiler) ===|
In instantiation of 'T List<T>::insert(T) [with T = std::basic_string<char>]':|
|55|required from here|
|44|warning: no return statement in function returning non-void [-Wreturn-type]|
||=== Build finished: 0 error(s), 3 warning(s) (0 minute(s), 0 second(s)) ===|
||=== Run: Debug in Review (compiler: GNU GCC Compiler) ===|

I got those warnings after exiting the console window.
Last edited on
anyone else know what I'm doing wrong here?
Lin 34: T is the result type, but you return nothing. Change to void List<T>::insert(T val) // Note: void
It's not a crash it's just a warning.

In you insert(...) function you're not insert anything. All you're doing is setting the head once. After that the data is lost.
Hey coder thanks for that. Changing T to void fixed my whole program and it ran perfectly.
Topic archived. No new replies allowed.