0

I want to convert a (simple linked) list into a skiplist which is derived from linked list. Inside the conversion ctor which gets a (linked-)list as param, i get a stackoverflow at *. I just call that ctor from main once. How is it possible that new SkipList is called loopwise?

class SkipList : public List {
public:     
    SkipList(SkipListEl* first) : List (first){};

    SkipList(const List& sl){                           
        ListEl* fst = sl.getFirst();
        new SkipList(fst);         // * <- stackoverflow

        while(fst->hasNext()){
            new SkipListEl(*fst);
            fst = fst->getNext();
        }
    };
user972851
  • 191
  • 1
  • 17
  • 1
    Does SkipListEl inherit from ListEl? It seems that List has a constructor taking a ListEl* as an argument; therefore, when you call new SkipList(fst), you are calling new SkipList(List(fst)), therefore leading to an endless recursion. – Frank Schmitt May 18 '12 at 20:16
  • Yes SkipListEl inherit from ListEl, but doesn't from List! Why can it call a ctor with argument List? I expected to call the base class ctor throught the first SkipList ctor... – user972851 May 19 '12 at 07:53

1 Answers1

2

You need to review your basic C++ rules on dynamic object creation. new calls the constructor for the object you're creating. By calling new object in the constructor for object, you're getting an infinite loop (infinite recursion, actually) leading to no more stack space.

Mahmoud Al-Qudsi
  • 28,357
  • 12
  • 85
  • 125
  • My intend was to call the first ctor from the second. Could you give me an advice whats wrong. – user972851 May 19 '12 at 07:58
  • See this: http://stackoverflow.com/questions/120876/c-superclass-constructor-calling-rules and it would probably be a good idea to pick up a book on C++ inheritance. – Mahmoud Al-Qudsi May 19 '12 at 17:04