-2

I have a series of classes that need to reference each other like this

class A
{
     vector<B *> B_list;
     vector<C *> C_list;
     ... 
};

for each class. I'm currently using one header file for all .cpp files which looks like this:

class B; class C; class A {...}; class B {...}; class C{...};

I'm wondering if there's a way to have one header per class.

Edit for clarity: I'm starting a project and need three pretty large, detailed, and distinct classes that each interact with each other frequently.

I have created minimal code for each class like this class A { C *c_item; B *b_item; } A; that includes the other classes and each header hass a blank .cpp file. Compiling it results in undefined type errors because no class can be defined without the others.

So, I added in forward declarations to each class header like class C; class B; which results in 'C' does not name a type errors and in my original code, I got a few class already defined errors when I was messing around with forward declarations.

The only way I could get everything working was to use one header file like I said above. I then tried using three separate headers that all included one header with forward declarations class A; class B; class C; and that didn't fix anything.

Edit 2, found the issue: I was writing class A {...} A;and now I'm writing class A {...}; with the forward declarations at the top of each file and it's working, but I'm not sure why that difference made it work.

  • What problems did you face when you tried placing the class definitions in different headers? – Ted Lyngmo Dec 26 '20 at 06:14
  • 1
    Whether having one header per class makes sense or not depends on the details of what is in each class. Nothing in the code you posted says you shouldn't have one header per class, so you need to describe in a bit more detail the problems you faced. – john Dec 26 '20 at 06:19
  • 1
    https://stackoverflow.com/questions/625799/resolve-build-errors-due-to-circular-dependency-amongst-classes – πάντα ῥεῖ Dec 26 '20 at 06:20

1 Answers1

0

Yes, you can have one header per class, for the class A header, type #include "classB.h" at the top and for the class B header type "include "classC.h" in that and then you should have 3 separate header files and the code you wrote should be fine.