0

I created a Node class for a linked list in C++:

template <class T> class Node {
public:
    T val;
    Node* next;
    Node(T val) {
        this->val = val;
        this->next = nullptr;
    }
    ~Node() {
        Node<T>* temp = this->next;
        if (temp != nullptr && temp->next != nullptr)
            delete(temp->next);
    }
};

And when trying tp initialize it:

definition: 
Node<Device>* devices;
code (in function):
this->devices = new Node<Device>({ this->serial_counter, name });

I get this error:

Error C2512 'Device': no appropriate default constructor available Gym c:\users\amitm\onedrive\מסמכים\visual studio 2015\projects\gym\gym\node.h 7

Line 7:

Node(T val) {

Also, if needed, this is the "Device" constructor:

Device::Device(int id, char* name) {
    this->id = id;
    strcpy(this->name, name);
}

How can I fix this error? I looked on-line for over an hour and cannot find a solution that works for me.

101010
  • 41,839
  • 11
  • 94
  • 168
Amit
  • 5,924
  • 7
  • 46
  • 94
  • 3
    Have you tried coding in a default constructor maybe? Might do magics. – DeiDei Nov 14 '15 at 13:15
  • 1
    I did now, and it worked, but this i do want to construct it with data. an empty constructor won't be exactly what I need. – Amit Nov 14 '15 at 13:19
  • You don't need to write linked-list classes in C++. Use `std::list`. – Christian Hackl Nov 14 '15 at 13:20
  • I know I have the std::list, but this is an excercise from Uni, and this is the requirement. (and if I go and see how std::list is implemented, I will pretty much copy it) – Amit Nov 14 '15 at 13:23

1 Answers1

7

The problem is that your value of type T is initialized in your constructor, and you then try to assign a new value. If you want to remove the error message, you need to initialize your value yourself:

Node(T v)
: val(v)
, next(nullptr)
{}

You can have more information here.

Adrien Hamelin
  • 395
  • 3
  • 9