I'm building a molecular dynamics simulation from scratch to practice my new c++ skills and I've run into some trouble.
Inside the simulation 'box' object, I have a private variable L that contains the length of the system. Also Inside 'box' object I have a vector of 'particle' objects (not derived in any way from 'box'). A 'particle' object contains the particle's normalized position (0 to 1 in each dimension). I need a way to access L from within the 'particle' object. I need this so that I can use it to multiply the normalized position in order to get the actual position when needed (the normalized position is more convenient to work with most of the time).
This access to L should be read-only, and not generate a copy of L, but rather all particles should refer to the same L in case it is changed (e.g. box is expanded).
I thought of maybe passing to each 'particle' object a const reference to L when they are initialized. Is this really the best way? Is there a way to do it that doesn't involve passing something to each 'particle' object in its constructor? (because I might have to pass many more such "state variables" to each 'particle')
Thanks.
Edit: I'm attaching code and addressing @1201ProgramAlarm 's suggestion which seems to make sense but I had problems implementing:
Particle_Class.h
class Box_Class;
class point;
class Particle_Class
{
public:
Particle_Class(Box_Class &box);
private:
const Box_Class &box;
point velByL;
};
Particle_Class.cpp
Particle_Class::Particle_Class(Box_Class &box)
:box(box){}
void Particle_Class::init_P(const point pt){velByL=pt*box.get_L()/mass; return ;};
Box_Class.cpp
for (int i=0;i<initN;i++)
particle.emplace_back(*this);
Unfortunately I get a compiler error at the line void Particle_Class::init_P
"error: invalid use of incomplete type 'const class Box_Class'|"
You can pass a pointer to the box
object to the particle
objects, and provide a getter method in box
for L
. This pointer could be passed in to the constructor of particle
, and stored within the object, or can be passed to the member functions of particle
that need access to it.