0

I am trying to practice a little bit with cpp and want to make a class of linked list and than to manipulate it reverse it, finding circle and etc. but I can't understand what is the problem with my ctor/

I have this main:

#include "list.h"
#include <iostream>


using namespace std;


int main () {
  int x = 10;

  ListNode<int> node4();
  ListNode<int> node3(10 ,node4);
}

while this is "list.h" :

#ifndef LIST_NODE_H
#define LIST_NODE_H

#include <iostream>
using namespace std;

template <class T>
class ListNode {

  ListNode* next;
  T data;

 public:

  ListNode<T>( T dat = 0 ,const ListNode<T> &nex = NULL):data(dat),next(nex){};

};

#endif

I can't understand why this line: ListNode<int> node3(10 ,node4); makes this errors, what is the problem?

list.cpp: In function ‘int main()’: list.cpp:12:33: error: invalid conversion from ‘ListNode ()()’ to ‘int’ [-fpermissive] list.h:15:3: error: initializing argument 1 of ‘ListNode::ListNode(T, const ListNode&) [with T = int]’ [-fpermissive] list.cpp:12:33: warning: passing NULL to non-pointer argument 1 of ‘ListNode::ListNode(T, const ListNode&) [with T = int]’ [-Wconversion-null] list.cpp:12:33: error: recursive evaluation of default argument for ‘ListNode::ListNode(T, const ListNode&) [with T = int]’ list.h:15:3: warning: in passing argument 2 of ‘ListNode::ListNode(T, const ListNode&) [with T = int]’ [enabled by default] list.h: In constructor ‘ListNode::ListNode(T, const ListNode&) [with T = int]’: list.cpp:12:33: instantiated from here list.h:15:76: error: cannot convert ‘const ListNode’ to ‘ListNode’ in initialization

0x90
  • 39,472
  • 36
  • 165
  • 245

3 Answers3

3

You have a number of errors with your code:

  1. In your constructor you have a null reference as your default value, which is invalid (see here).

  2. For a constructor with no arguments you need to omit the () (you can read about why here)

Something like this should work:

using namespace std;

template <class T>
class ListNode {
    ListNode* next;
    T data;

    public:
          ListNode<T>( T dat = 0 ,ListNode<T> * nex = NULL):data(dat),next(nex){};
};


int main(){
    ListNode<int> node4;
    ListNode<int> node3(10, &node4);
}
Community
  • 1
  • 1
GWW
  • 43,129
  • 11
  • 115
  • 108
2

There are a couple of problems here.

  • First you don't need ListNode<T>() simpley ListNode(...) for the constructor.

  • Second you can't have a defalut for a reference parameter to null if there is the potential for nex to be null it needs to be a pointer.

rerun
  • 25,014
  • 6
  • 48
  • 78
0

Default parameters are evil (IMO).

(just a thought) Create different constructors (one with no parameters, one with parameters, ... )

Max
  • 3,128
  • 1
  • 24
  • 24