Kushan Mehta
Kushan Mehta

Reputation: 188

Best way to implement a global variable for use in class in c++

Please read the question before marking it as a duplicate.
So here is what I am trying to achieve. Basically I have a string which contains some value initially.
I have split my program into many classes for modularity.(you can suggest a better way to do that - currently each file contains one class in it)
So say for eg I want to operate on the data with class1 , then the modified string needs to get operated by class2 and so on.

eg. Initial entry is "hello world"
first class -> "hello WORLD"
second class -> "H@l@o WORLD"
thiid class -> "#@l@o WORLD"
and so on...

Reading everywhere that global variables are a big no no when coming to issues and downsides it has. So keeping that in mind what would be the best way I can share seamlessly between classes.
I also thought of passing the string as a pointer to each function but I thought there might be better alternatives to it. Please suggest.
Thanks for stopping by to read my que and help me out.

Upvotes: 2

Views: 3071

Answers (1)

Chris Drew
Chris Drew

Reputation: 15334

Without knowing exactly why you want to do this it is hard to answer. But I don't see what is wrong with just passing the string as a reference to each class much like you suggest:

class StringModifier1 {
public:
  void operator()(std::string& s) {
    // modify s...
  }
};
class StringModifier2 {
public:
  void operator()(std::string& s) {
    // modify s...
  }
};
class StringModifier3 {
public:
  void operator()(std::string& s) { 
    // modify s
  }
};

int main() {
    std::string myString = "hello world";

    StringModifier1 modifier1;
    StringModifier2 modifier2;
    StringModifier3 modifier3;

    modifier1(myString);
    modifier2(myString);
    modifier3(myString);
}

Live demo.

In some cases you might want the classes to store a pointer or reference to the string:

class StringModifier1 {
private:
 std::string& s;

 void func1() { 
     // modify s... 
 }
 void func2() { 
     // modify s some more...
 } 
public:
  StringModifier1(std::string& s) : s(s) {}

  void execute() { 
      func1();
      func2();        
  }
};

int main() {
    std::string myString = "hello world";

    StringModifier1 modifier1(myString);
    modifier1.execute();

    StringModifier2 modifier2(myString);
    modifier2.execute();

    StringModifier3 modifier3(myString);
    modifier3.execute();
}

Live demo.

You might want one class to own and provide access to the string and the other classes have a pointer or reference to the owning class.

Upvotes: 1

Related Questions