Sriram Nagaraj
Sriram Nagaraj

Reputation: 11

Why isn't the static variable getting modified

I'm creating a static variable 'a' inside a member function getobj() and returning it by reference and capture the reference in b. And I modify the same static variable 'a' in another member function mod(). When I print b, I should be expecting '2' right? Why isn't the static variable 'a' not modified to 2?

#include <iostream>

using namespace std;

class Test {
  
  public:
  int& getobj() {
    static int a = 1;
    return a;
  }

  void mod() {
    static int a = 2;
  }

};

int main(int arc, char* args[]) {

  Test t;
  int &b = t.getobj();
  cout << "printing b first time and its value is expected : " << b << endl;
  t.mod();
  cout << "printing b second time after modifying and its value has not changed : " << b << endl;
  return 0;
}

Output observed is

printing b first time and its value is expected : 1
printing b second time after modifying and its value has not changed : 1

Upvotes: 0

Views: 363

Answers (2)

MikeCAT
MikeCAT

Reputation: 75062

The variable a in getobj() and the variable a in mod() are in different scope and are different things.

Therefore, modification to a in mod() won't affect a in getobj().

Upvotes: 5

Bathsheba
Bathsheba

Reputation: 234715

You could achieve your aim with the following piece of computational devilry:

void mod() {
    static int& a = getobj();
    a = 2;
}

Currently you have two different ints, both with static storage. Changing one will not change the other.

But did you want to use a class member variable instead (which is the normal thing to do), perhaps even without static storage duration?

Upvotes: 2

Related Questions