Working around Global Variables and Pointers

5 views (last 30 days)
I am implementing a physical problem using OOP. I have two classes called "Room" and "Particle". Room as properties like temperature, volume, etc. Particle have properties such as mass, velocity, position, etc. I start by defining a Room object and giving it properties. I then define thousands of Particle object that are supposed to move around in the room depending on the properties of the room and the particle. To simulate the movement of a given particle, I've defined a method in the "Particles" class called "MoveParticle". Everytime I call this function, the particle moves.
The MoveParticle method depends on the properties of the room that the given particle is in. How can I access this data (properties of the Room object) as the particle and room are different objects?
In C/C++, I would define a pointer in the "Particles" class that points to a specific "Room" object, so that whenever I want to access properties in of the Room object, the pointer can go and access it. But I don't think I can do this in MATLAB.
Another work around would be to define the Room object as a global variable, however, that seem to be considered a bad practice.
Other alternatives is to pass the Room object as a argument in the MoveParticle method or include Room object as a property in the Particle class. However, that seems to be computationally inefficient since a copy of Room object is created in every Particle object which consumes a lot of memory.
Thanks a lot.

Accepted Answer

Steven Lord
Steven Lord on 9 Nov 2022
Since each Particle and each Room represent a unique physical object they should probably be handle classes with handle semantics. Each Particle could have a property representing the Room that contains it and each Room could have a property holding an array of the Particle objects inside it.
So if P was a Particle and R the Room it's in, the moveParticle method called on P could reference P.containingRoom.Size to get the Size property of R from P's property containingRoom.
  1 Comment
Roshan Mathew Tom
Roshan Mathew Tom on 9 Nov 2022
That's seem to be exactly what I was looking for. Thank you.

Sign in to comment.

More Answers (0)




Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!