Home > other >  How can I have a local variable that persists over time but is not shared among all members of the s
How can I have a local variable that persists over time but is not shared among all members of the s

Time:08-09

I am programming c in Unreal Engine. I have some functions that use variables whose value I need to last in time and that are only used within that function. The problem is that if I declare them as static local variables, when I have several members of the same class they all share the same value, and I would like each class to have its own instance of a local variable that lasts over time. How can I achieve this?

CodePudding user response:

If you really want that level of encapsulation, you could make a separate class for each of your member variables and put the function(s) that operate on that variable in that class. You can then inherit from any number of those separate classes to build a class that has several variables.

Example:

struct func_x {
    func_x(int X) : x{X} {}

    int function_using_x() {
        return x;
    }

private:
    int x; // only one member variable
};

struct func_y {
    func_y(int Y) : y{Y} {}

    int function_using_y() {
        return y;
    }
    
private:
    int y; // only one member variable
};


struct foo : func_x, func_y { // inherit from both
    foo(int x, int y) : func_x(x), func_y(y) {}
};

Usage:

#include <iostream>

int main() {
    foo f{1, 2};
    std::cout << f.function_using_x() << f.function_using_y() << '\n'; // 12
}

CodePudding user response:

you need 2 variables for that. one for counter (declare local but nut static) and change in one instance and another static for following the first variable;

but notice every time you need that static you should update it

  • Related