Question
I came from Java to C++ ...
When I try to do this ...
class Box {
Table* onTable;
};
class Table {
Box* boxOnIt;
};
int main() {
Table table;
Box box;
table.boxOnIt = &box;
box.onTable = &table;
return 0;
}
the compiler tell me that Table is undefined. If I switch class definitions the compiler tell me that Box is undefined
In java I was able to do something like this with no problem. Is there a solution for this to work? thanks...
Solution
You have a circular dependency here and need to forward to declare one of the classes:
// forward declaration
class Box;
class Table
{
Box* boxOnit;
} // eo class Table
class Box
{
Table* onTable
} // eo class Box
Note that, generally speaking, we'd have a separate header file for Box
and Table
, using forward declarations in both, e.g:
box.h
class Table;
class Box
{
Table* table;
}; // eo class Box
table.h
class Box;
class Table
{
Box* box;
}; // eo class Table
Then, include the necessary file in our implementation (.cpp) files:
box.cpp
#include "box.h"
#include "table.h"
table.cpp
#include "box.h"
#include "table.h"
OTHER TIPS
you should use forward declarations. just mention this as your first statement:
class Table; // Here is the forward declaration
Add this before class Box:
class Table;
Thus you forward declare class Table so that pointer to it can be used in Box.
class Table;
class Box {
Table* onTable;
};
class Table {
Box* boxOnIt;
};
int main() {
Table table;
Box box;
table.boxOnIt = &box;
box.onTable = &table;
return 0;
}
Use forward declarations so that the class declared first knows about the second one. http://www.eventhelix.com/realtimemantra/headerfileincludepatterns.htm
You should forward declare one of the two classes:
class Table; // forward declare Table so that Box can use it.
class Box {
Table* onTable;
};
class Table {
Box* boxOnIt;
};
int main() {
Table table;
Box box;
table.boxOnIt = &box;
box.onTable = &table;
return 0;
}
or viceversa:
class Box; // forward declare Box so that Table can use it.
class Table {
Box* boxOnIt;
};
class Box {
Table* onTable;
};
int main() {
Table table;
Box box;
table.boxOnIt = &box;
box.onTable = &table;
return 0;
}
Add class definition on the top
class Table;
class Box {
Table* onTable;
};
class Table {
Box* boxOnIt;
};