0

I'm looking for a way to have an int variable that persists value across method calls. From this perspective a class member will be good.

But I would like that int variable to be changed in only one particular method.

How do I make that?

I tough about

void MyClass::my_method(){
    static int var = 0;
    var++;
}

But, I would like var = 0; to be executed only the first time.

KcFnMi
  • 5,516
  • 10
  • 62
  • 136

4 Answers4

3
void my_method(){
    static int var;
    var++;
}

The problem here is, that

    static int var;

is only visible in the local scope of my_method().

You can make it global just by definition of that variable outside of my_method():

int var;
void my_method() {
    var++;
}

but var will be visible for everyone.


The better way is to encapsulate all of that into a class:

class MyClass {
public:
     static void my_method() {
         var++;
     }
private:
    static int var = 0;
};
πάντα ῥεῖ
  • 1
  • 13
  • 116
  • 190
2

You can use the following key access pattern:

struct Foo {
  void fun1();
  void fun2();

  static class Var {
    friend void Foo::fun1();
    int i = 0;
  public:
    int value() const { return i; }
  } var;
};

Foo::Var Foo::var;

void Foo::fun1() { var.i = 42; }

void Foo::fun2() { 
  // var.i = 42; // this will generate compile error cause fun2 doesn't have to var 
}

Live Demo

This way only the member functions of Foo that are declared friends in wrapper class Var can change its private member variables (e.g., var.i).

101010
  • 41,839
  • 11
  • 94
  • 168
0

var is just locally, if you want that to be 0 the first time the function returns make it initialized to -1 or if 0 is just right you are ok. As is var is only visible inside my_method so if you want that to be visible to all the class you have to put it outside and use only my_method to modify the value.

GMG
  • 1,498
  • 14
  • 20
0

I don't have enough rep to comment yet, But you should note that Static is not equal to Constant.

Static variables maintain their value for ALL instances of a class, whereas Constant variables can have different values for each instance (object) of a class.

See this question for a more in-depth explanation. What is the difference between a static and const variable?

To answer your question directly, you cannot have a true "Global" vairable that is only editable from one class. Instead, you should consider πάντα ῥεῖ 's answer OR wait to declare the constant until after you know the value you would like to assign to it. For instance, I want to store X+10 to a constant variable Y

int x = 5 //create variable

//Do whatever you need to do to get the value
function myFunction(){
    x = x + 10;
}

const int y = x; //now Y = 15 and cannot be changed.  
Community
  • 1
  • 1
Native Coder
  • 1,792
  • 3
  • 16
  • 34