Search code examples
javac++linked-listsingly-linked-listcode-translation

C++ LinkedList ListElement class header file trouble


I'm pretty new to C++ and because I'm very interested in learning this language I'm trying to translate my old Java projects into C++. One of them is basic LinkedList, which is supposed to store objects of class "ListElement" containing objects of class "Table" (basically a list of tables for a restaurant). So far I could translate the Table class without any errors. Everything by rules (class declaration in the header file "Table.h", implementation in the sourcecode file "Table.cpp"). In the main.cpp I can create an instance of Table, manipulate the data and print it out. So for me Table class seems to work as it does in Java. When it comes to ListElement class I'm having trouble at specific point and I don't know what I'm doing wrong in C++ because in Java it is working well like that. Basically it seems to be a declaration problem, which I can't honestly figure out; so that is why I need your help here.

Here is what my ListElement.h looks like:

#ifndef ListElement_h
#define ListElement_h

#include "Table.h"

class ListElement{
private:
    Table value;
    ListElement next;
public:
    Table getValue();
    void setValue(Table value);
    ListElement getNext();
    void setNext(ListElement next);

    //Default-Constructor
    ListElement();
    //Custom-Constructor
    ListElement(Table value, ListElement next);
    //Destructor
    ~ListElement();
};

#endif /* ListElement_h */

The problematic part seems to be this part of code:

   ListElement next;

(I'm using XCode on Mac OSX) My IDE gives me following error: "Field has incomplete type 'ListElement'"

My ListElement.cpp looks like this:

#include "ListElement.h"
#include "Table.h"

ListElement::ListElement(Table value, ListElement next){

}
ListElement::ListElement(){

}
ListElement::~ListElement(){

}

And in my ListElement.cpp I get following error in my IDE: "Exception specification in declaration does not match previous declaration"

In Java I've got ListElement like this (basically only the important part of the code):

public class ListElement {
    private Table value;
    private ListElement next;

and it works just fine.

Am I missing something or what am I doing wrong?


Solution

  • In java private ListElement next; creates only a reference to another object of type ListElement.

    But in C++, this is not the case. In every object of type ListElement, another object of type ListElement is created thus creating an infinite recursion.

    You can create a pointer to another ListElement using

    ListElement * next;