0

This is my header file

#ifndef LinkedList_H
#define LinkedList_H

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

class LinkedList {
    public:
    int length;
    // pointer to the first element of LinkedList
    Node *head = 0;
    // pointer to the last element of LinkedList
    Node *tail = 0;

    LinkedList();

    ~LinkedList();
};

#endif

and this is my.cpp file

#include "LinkedList.h"

using namespace std;

LinkedList::LinkedList() {
    head=tail;
    this->length=0;
}

LinkedList::~LinkedList() {
    Node *current = head;
    while(current!=NULL){
        Node *temp = current;
        current=current->next;
        delete temp;
    }
}

void add(string _name, float _amount){
    Node *node = new Node(_name, _amount);
    while(head==NULL){ //here, there is an error.
        head=node;
        head->next=tail;
    }
}
int main(){
    LinkedList *list = new LinkedList();
    add("Adam", 7);
    cout<<list->head<<endl;
}

In my .cpp file when I want to try to make an add function, it gives me an error in the while loop condition in add function. It says "head was not declared in this scope". But I declared in .h file. I couldn't see what is wrong.

gsamaras
  • 71,951
  • 46
  • 188
  • 305
Ahmet
  • 21
  • 2
  • 1
    Make sure that `Node.h` does not include `LinkedList.h`. if it does you have a circular include path that needs to be broken. – drescherjm Oct 15 '18 at 17:22
  • https://stackoverflow.com/questions/625799/resolve-build-errors-due-to-circular-dependency-amongst-classes – drescherjm Oct 15 '18 at 17:35
  • `void add(string _name, float _amount){` you are declaring a free function that has no relation to your class `LinkedList`. – drescherjm Oct 15 '18 at 18:01

2 Answers2

2

You should use the resolution scope operator, just like you did for the constructor and the destructor.

So, you in your source file do this:

void LinkedList::add(string _name, float _amount) {

And then, of course, declare that function inside your class, in the header file.

gsamaras
  • 71,951
  • 46
  • 188
  • 305
0

Very likely the problem is circular includes. You probably have Node.h including LinkedList.h and vice-versa. This leads to (essentially) a paradox: If both class definitions require the other, which of the two is defined first in any given compilation unit?

In practice, you include Node.h, which then tries to include LinkedList.h again (note that #include literally means "copy-paste this file here" to the compiler), but at this point LinkedList_H is already defined (because that's where you came from) and the include has no effect. So now you are in the middle of Node.h but with no prior definition of LinkedList and get "not declared" errors.

The solution is to remove the #include Node.h in LinkedList.h and replace it with a forward declaration, since the LinkedList definition in the header doesn't need to know anything more than "the class Node exists" (because it only uses pointers).

Max Langhof
  • 23,383
  • 5
  • 39
  • 72