I have a C++ code that performs simulation of a physical system which deals with motion of objects. It has the following classes:
-
Class
Main
, containing all the main calculation methods and the data pertaining to the state of the physical system and the simulation (e.g., positions and velocities of objects). It is instantiated only once. -
Class
A
, which contains specific functionality that may be needed in particular situations (for instance,A
can represent the effect of a particular phenomenon that might affect motion, e.g., wind). It is an optional functionality that may be enabled or disabled by the user.A
is also instantiated only once.
Class A
requires access only to a small subset of the data members of Main
(e.g., it might not care about the positions but it does need to know the velocities). It also needs to be able to modify them.
My current solution is to define a unique pointer to A
as a data member of Main
and create A
in the constructor of Main
:
m_A = std::make_unique<A>(arg1, arg2, ...);
where arg1
, arg2
, etc., are data members of Main
.
However, this approach has the following drawbacks:
-
Sometimes, when I want to extend the functionality of
A
, I may need to gain access to additional data members ofMain
. This requires the redefinition of the constructor signature ofA
. It also makes the list of arguments passed toA
pretty long (depending on how complex the functionality ofA
is). The latter problem can perhaps be solved by gathering the different arguments in a single struct, but I am not sure if this is a good solution. -
In the future, I might want to create another class
B
that would implement some other functionality, much likeA
. However, unlikeA
, it might need access not only to the data members ofMain
but also to some ofMain
methods. In this case, I see no other option than passing a reference toMain
to the constructor ofB
(e.g., using*this
). However, I would almost certainly never use all the methods ofMain
inB
(but only a small subset of them).
Question: Given these requirements, what is the most optimal way to organize the classes and the communication between them? Is there some design pattern that suits this problem better? I prefer a solution that does not impact performance too much but also allows flexibility (for future extensions).
grjj3 is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.