I want to create a class which has a static method that returns a reference to a static variable(which is declared inside the method). What I want is when calling the method to get the reference of the static variable. Then when I modify it outside the class and call the method again to get the same value I previously set.
Here's what I tried:
#include <iostream>
using namespace std;
class A
{
public:
static int& f()
{
static int i;
return i;
}
};
int main()
{
static int i;
i = A::f();
cout << i << endl;
i = 11;
cout << i << endl;
i = A::f();
cout << i << endl;
return 0;
}
The problem is that the output of this code is:
0
11
0
Press <RETURN> to close this window...
Why doesn't it return 0, 11, 11 and how can I make it return 0, 11, 11?
Note: I want the static variable to be explicitly declared inside the method and not as member.
Thanks!
This is because you copy the value returned by reference into a regular variable: when you store int& in an int, it is no longer a reference.
What you should do instead is
int &i = A::f();
Note that the local i needs not be static: reference to static data can be stored in automatic variables without a problem.
To have the local variable i refer to the same variable inside the function, declare it as a reference:
static int& i = A::f();
Otherwise, you're just creating a new variable and using assigning A::f() to it.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With