c++ - Why can't I use arrow operator in initialization list? -


i'm beginner in c++. when practicing writing linked list, tried use initialization list class constructor assign null head->next.

in class contructor warned arrow operator "expected '(' or '{'". why there such error? (i know can initialize class members in block, why can't this pointer?) thanks!

here's header file linkedlist:

linkedlist.h

#include <iostream> using namespace std;  struct node { int val; node *next; };  class linkedlist { private: node *head; int listlen;  public: linkedlist(); void insert(node*, int); void del(node*); void reverse(node*); void traverse(node*); int random(); ~linkedlist();  }; 

and here's class constructor:

linkedlist.cpp

#include "linkedlist.h" #include <iostream>  linkedlist::linkedlist() :listlen(0), head->next(null){} 

in general can initialize members part of initialization lists. if issue here, initialize next-pointer null part of body of ctor. however, member variable head pointer, , not pointing anywhere, suspect wanted set head null (or nullptr if you're using c++11 or later):

linkedlist::linkedlist() :listlen(0), head(null) {}

you consider additionally adding ctor struct node initialize next null upon initialization.

a few other things thought worth pointing out since said you're new:

  1. note initialization lists aren't run in order written in ctor, rather in order members defined in class' body. in case here listlen initialized 0 after head initialized. doesn't matter code here, matter if initialization of members more complex , has dependencies. personally, i'd recommend keep order of initialization lists matching order of member definitions. compilers have flags warn if not case.

  2. rather implementing own linked list, have considered using data structure standard library? check out cppreference.com lots of great information it. in particular, check out 'list', 'vector', or 'deque' depending on use case.


Comments

Popular posts from this blog

python - How to insert QWidgets in the middle of a Layout? -

python - serve multiple gunicorn django instances under nginx ubuntu -

module - Prestashop displayPaymentReturn hook url -