I have two classes which both need to have links to objects of one another. Here's some example code to show my issue:
//object1.h
class object1{
object2 *pointer;
}
My other class:
//object2.h
class object2{
object1 *pointer;
}
I'm not exactly sure how I'm supposed include the two classes simultaneously in each other's file. Having an include for the other class in both files is causing me issues. Preferably, I would like to just have both the objects in one file, since their headers are only a few lines of code each, but this causes an error on whichever class is first declared in the file, since the other class header isn't preceeding it; It gives me an invalid type error.
Use a forward declaration:
A forward declaration introduces an incomplete type. In short, it tells the compiler that the definition exists somewhere else. You have some limitations with incomplete types, though. Since the compiler doesn't know its full definition, it cannot do things like allocating enough space for it, invoking member functions, checking the virtual table, etc. Fundamentally, what you can do is to just declare references/pointers to them and pass'em around:
A good pattern is to use forward declarations to break dependency cycles between headers or class definitions and make you wonder whatever your design could be improved.