I am working on a C++ project which has been created by C developers years ago.
First of all you have to know some restrictions I have in this project:
- no dynamic memory allocation is allowed
- all objects are generated in a global "builder" file. In this file the objects are also connected by references when calling the constructors.
I have some issues sharing data between objects because of the architecture. Let me give you an example:
A.h
class A
{
private:
dataStructA data;
}
B.h
class B
{
private:
dataStructB data;
}
C.h
class C
{
private:
dataStructC data;
}
D.h
class D
{
private:
dataStructD data;
}
The objects are all responsible for some data structures which need to be accessed by the other objects. Therefore I have to connect them in the previously mentioned builder file like:
builder.cpp
A(&B, &C);
B(&D);
C(&A, &D); //and so on...
This is really ugly so I want to ask you how I can do it better.
My first approach was to specify one of the classes as my main class which holds references to all other classes:
A.h
class A
{
private:
dataStructA data;
B& b;
C& c;
D& d;
}
The subclasses then must also know the main class (A in this example) to access the other data structures. Sadly doing this without dynamic memory allocation results in circular dependencies and lot of problems. So I stopped it.
How would you solve this problem?
Extra questions: How would you solve it WITH dynamic memory allocation? Maybe I get a good arguement to refactor it in the future.
Thanks and greetings