2

I have been having a lot of trouble with my headers and making sure everything is declared correctly. First off my files:

//Main.cpp
#include "Item.h"
#include "Warehouse.h"
using namespace std;

int main() {
    ...
}

//Item.h
#ifndef ITEM_H
#define ITEM_H
#include <string>
using namespace std;

class Item {
    ...
};
#endif  /* ITEM_H */

//Item.cpp
#include "Item.h"

//Warehouse.h
#define WAREHOUSE_H
#ifndef ITEM_H
#define ITEM_H
using namespace std;

class Item;
class Warehouse {
    ...
private:
    Item* array; //problem starts with this
};
#endif  /* WAREHOUSE_H */

//Warehouse.cpp
#include "Warehouse.h"
#include "Item.h"

Warehouse::Warehouse() {
    array = new Item[arraySize]; //and this is where I get the error
}

I am pretty sure the problem has to do with my header in Warehouse.h but every combination I try does not work. Sorry if not enough of the code is posted but I figure the problem is with the includes and declarations.

Thanks ahead of time.

edit: to clarify this is not in one file. I just wrote it like this to simplify things. Each one of the above is a separate file.

rerx
  • 1,133
  • 8
  • 19
tmricks94
  • 35
  • 1
  • 6

2 Answers2

3

Your include guards in the header file Warehouse.h are not correct.

Instead of

//Warehouse.h
#define WAREHOUSE_H
#ifndef ITEM_H
#define ITEM_H
using namespace std;

// ...

#endif  /* WAREHOUSE_H */

you want

//Warehouse.h
#ifndef WAREHOUSE_H
#define WAREHOUSE_H
using namespace std;

// ...

#endif  /* WAREHOUSE_H */

With the current version the class definition in item.h is never included in Warehouse.cpp because the mixed-up include guards in Warehouse.h prevent item.h to be read due to the order of

//Warehouse.cpp
#include "Warehouse.h"
#include "Item.h"    //Warehouse.cpp
#include "Warehouse.h"
#include "Item.h"

Then the compiler does not know the definition of Item at that point, hence the error.

Another thing: Do not form the habit of using namespace std in header files. This will lead to issues at some point.

rerx
  • 1,133
  • 8
  • 19
0

Problem is not in this declaration

private:
    Item* array; //problem starts with this

You may define a pointer to an incomplete type.

I think the problem is in a statement where you try to allocate an object for this pointer using operator new or to dereference the pointer.

Also I do not see any reason why you do not want to include header Item.h in header Warehouse.h instead of using elaborated name

class Item;
Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335