Search code examples
c++compiler-errorsfriend

invalid use / forward declaration of 'struct Node'


For a school project I am trying to make a binary search tree at the same time we are supposed to learn how to use 'friendship' in classes. The errors I get while compiling are: [I put comments in code where the errors originate from for clarity]

$ make -f makefile.txt
g++ -Wall -W -Werror -pedantic -g -c BST.cpp
BST.cpp: In member function `void BST::insert(std::string, std::string)':
BST.cpp:13: error: invalid use of undefined type `struct Node'
BST.h:19: error: forward declaration of `struct Node'
makefile.txt:9: recipe for target `BST.o' failed
make: *** [BST.o] Error 1

Basically I want to be able to access the Node class as if the class was nested (I am not allowed to nest it for the sake of this programming assignment however). Obviously simply using 'ptr->m_data' would not work, but what could I do to make it work?

Node.h

#ifndef NODE_H_INCLUDED
#define NODE_H_INCLUDED

#include <iostream>
#include <string>

using namespace std;

class BST;
class Node
{
public:
    Node(string key, string data)
    {n_key = key; n_data = data;}
    ~Node();
private:
    string m_key;
    string m_data;
    Node *m_left;
    Node *m_right;
    //Node *m_parent;
};


#endif // NODE_H_INCLUDED

BST.h

#ifndef BST_H_INCLUDED
#define BST_H_INCLUDED

#include <iostream>
#include <string>

using namespace std;

class BST
{
public:
    BST()
    {m_root = NULL;}
    ~BST();
    void insert(string key, string data);
    void find(string key);
    void remove(string key, string data);
    void print();
    friend class Node; //Error: forward declaration of 'struct Node'
private:
    Node* m_root;

};

#endif // BST_H_INCLUDED

Why is it that when I call the below line of code it reads out the above error messages? (Note: the below code is from BST.cpp)

#include "BST.h"

void BST::insert(string key, string data)
{
    Node* yPtr = NULL;
    Node* xPtr = m_root;
    while(xPtr != NULL)
    {
        yPtr = xPtr;
        if(key < xPtr->m_key) //Error: invalid use of undefined type 'struct Node'
        {

        }
    }
}

Solution

  • The compiler has not seen the definition of Node when it gets to that line in BST.cpp. Note that that is the first line where the compiler needs to see the structure of Node. You need to #include "Node.h" in BST.cpp.