Don't use a static variable inside a function in a class/struct. Is there a simpler alternative method?

Manda Rajo 141 Reputation points
2022-03-13T08:36:32.28+00:00

Hi, is there an alternative method instead of using static variable? And the code at bottom of this post explains how I want to use a simple method.

class MyClass {
public:
    void func() {
        static int value = 0; // Don't do it, example of how I may attempt to use it is with isUpdated.
        printf("%d\n", value);
        value++;
    }
};

int main()
{
    MyClass c1;
    MyClass c2;
    c1.func(); // Output: 0
    c2.func(); // Output: 1 but it's not 0, so don't use a static variable inside a function in a class/struct.

    _getch();
    return 0;
}

In the example below, I attempted to use 'static' which seems to be a very simple method, but I shouldn't use it. Does anyone knows another simpler method?
This is my current solution but I don't believe it's the simplest: Make that variable a member variable of the class Window, but the problem is I must initialize it in the constructor to choose what initial value should it be, and it's too far from the main code, but if I always do that for my entire project then it seems weird, I don't know if there's another better method.

void Window::event(const vec2 &displaySize, SDL_Event &sdlEvent, bool wantCaptureMouse)
{
    ModalEvent ev = {};

    // Update window rect
    setRect({ {0, 0}, displaySize });
    _xx.drawData->_drawData->DisplayPos  = { 0, 0 };
    _xx.drawData->_drawData->DisplaySize = { displaySize.x, displaySize.y };
    _xx.drawData->_drawData->FramebufferScale = { 1, 1 };

    // mousePos, mouseButtons and make ImGui windows to be the mouse obstacles
    static uint32_t mouseButtons_old = 0x0; // <---- This is an example of how I attempted to use 'static' inside the class Window, but there can be multiple windows.
    uint32_t mouseButtons = 0x0;

    ...
}
Developer technologies C++
{count} votes

Accepted answer
  1. Viorel 122.6K Reputation points
    2022-03-13T09:22:39.977+00:00

    In modern C++ you can define and initialise the member:

    class Window
    {
       uint32_t mouseButtons_old = 0;
    
       void Window::event(const vec2 &displaySize, SDL_Event &sdlEvent, bool wantCaptureMouse)
       {
          . . .
       }
    };
    
    1 person found this answer helpful.
    0 comments No comments

1 additional answer

Sort by: Most helpful
  1. Manda Rajo 141 Reputation points
    2022-03-13T09:47:50.4+00:00

    Viorel-1 > Thanks. I didn't know that method exists, I used it in a very far past but I forget. That's why forum is so helpful. I tried to Google the question before but there wasn't such answer. So thank you.

    0 comments No comments

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.