1

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.

3
  • 2
    You preferably don't. This is a symptom of too tightly coupled classes. Commented Sep 13, 2015 at 4:59
  • 1
    If you want to reserve zones for each class that uses the array, why not have each class have their own array? Commented Sep 13, 2015 at 4:59
  • 1
    Why 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 class Commented Sep 13, 2015 at 5:00

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.