How can we maintain a shared array for storing data using a static variable? There should be zones reserved for each class in the array. We should be able to access the array from all the classes to store and retrieve data.
-
2You preferably don't. This is a symptom of too tightly coupled classes.milleniumbug– milleniumbug2015-09-13 04:59:37 +00:00Commented Sep 13, 2015 at 4:59
-
1If you want to reserve zones for each class that uses the array, why not have each class have their own array?bku_drytt– bku_drytt2015-09-13 04:59:52 +00:00Commented Sep 13, 2015 at 4:59
-
1Why can't you have a separate private array in each class? It is better design than having a shared array with zones reserved for each classAndrej Adamenko– Andrej Adamenko2015-09-13 05:00:48 +00:00Commented Sep 13, 2015 at 5:00
1 Answer
It sounds like what you are asking for is a global variable -- which, as mentioned in the comments, is usually a bad idea, because when every class has read and write access to the same shared data, it becomes increasingly difficult to reason about the program's behavior (because it becomes hard to keep track of what parts of the codebase might be modifying or depending on the shared data, or how the different parts will interact with each other when accessing it).
That said, if you really want to do it (and it can work okay for very small/simple programs, if only because just about any approach can be made to work okay for very small/simple programs), you can do something like this:
// in my_shared_data.h (or some other header file than anyone can #include)
struct MyGloballySharedData
{
int myArray[100];
char myString[100];
// ... and whatever the data you care to add here
};
// tell all the #include-ers that (mySharedDataObject) exists, somewhere
extern MyGloballySharedData mySharedDataObject;
and
// in my_shared_data.cpp (or some other .cpp file, it doesn't matter which one)
MyGloballySharedData mySharedDataObject;
Note that you don't want to declare mySharedDataObject to be static, as that would make it accessible only to code that is located in the same .cpp file that the mySharedDataObject global is stored in, which would make it not-globally-usable.