I've really tried to make this work without using pointers. I want to create a shared class where two classes "see" each other and share this object. I wanted to initialize the shared object using an initializer list, but I'm getting these errors:
1 2 3 4
error: field ‘shared_type’ has incomplete type ‘shared’
note: forward declaration of ‘class shared’
note: forward declaration of ‘class class_A’
note: forward declaration of ‘class class_B’
The first error doesn't make sense because the constructor for shared exists in shared.cpp.
I have tried declaring shared_type in class_A and class_B as const shared& shared_type;, but that gave me an error saying that the lvalue is a const and the rvalue cannot be set to const, namely the value for the initializer.
Is there anything else I could try without using pointers?
First issue, class 'shared' contains a 'class_A'. class_A contains a shared. You have an "infinite recursion" of resources, which would blow up the size of your class to infinity.
Second issue,
1 2 3 4 5 6
class shared;
class class_A
{
public:
shared shared_type;
'shared shared_type' is an object within class_A that is being defined by value (i.e. not a reference or pointer), so the compiler needs to know the contents of shared to know how big to make class_A itself. Therefore, a forward declaration of class_A is not sufficient.
For the 'shared' object, you need to decide who 'owns' the object.
Is it
(1) class_A
(2) class_B
or (3) created outside of class_A or class_B.
You don't need to use pointers for this to work, but you would need to at least use references correctly (which are kinda like pointers that can't be null).
Here is one solution, which has a class that then depends on a resource by reference (which is a shared resource).
class_A and class_B are actually the same exact class logically, but I made them separate classes for purposes of example since I assume you want something about them to be different in your 'real' code.
Thanks, it's interesting how you didn't use a default constructor, that's the only thing that makes this work is that the constructors in both A and B have a parameter by reference.