Some notes on defining classes with mutual references to instances of each other:
The classes can’t hold the actual other class’s instance data, because that could potentially cause an infinite expansion memory allocation, so by definition, the classes should be defined to contain pointers to the instance of the other class.
The classes C++ header files can’t be including each other (it will cause a compile error), because, this is literally telling the compiler to endlessly read the files, each one including the other. So only one class header can have an “include” statement pointing to the other.
In order to successfully compile the class header file which doesn’t contain an “include” statement for the other class, a forward declaration of the other class is needed. I.E. a ‘ghost’ declaration of the class at the beginning of the file, just so the compiler ‘knows’ there is such an entity, and doesn’t throw an error.
Class A code:
Class B code:
Hope this was helpful! If you find mistakes or inaccuracies in this post I’ll be very grateful of you share them with me in the comments.
Steps for creating a new Visual Studio project based on existing code files:
Create an empty project folder and name it your intended project name.
Inside the new project folder, create a folder for your source code files. * I call is “Source”, not sure if it has to named that way..
Copy your existing code files to the source folder.
Launch Visual Studio, and open it without code:
Select: File > New > Project From Existing Code.. To open the Create New Project From Existing Code Files wizard:
Note: The documentation on this operation states that the wizard will copy files by itself, my own experience is that it doesn’t, it just links them to the project, that’s why I copy the source files prior to this step. In the Create New Project From Existing Code Files wizard, 1. Set the path to your project folder. 2. Specify a project name. * I set this to be the same name as the project folder name, not sure if otherwise it will create a sub-folder.. 3. This is set to the same folder as the project folder. * It’s possible that I don’t understand this correctly.. but I think theoretically, the intention is that you would add external folders to this list, from which source files would be copied, but like I said, when I tried that the files where not copied to the project.
Set your new projects settings and press Finish to create the new project: