Search code examples
c++mutable

Modifying a data of type "static const int* const" from a member function


TLDR Question:

class MyClass
{
public:
    void Modify()
    {
        //How can I modify MyData here 
    }

public:
    static const int* const MyData;
};

Lore:

I have a class like this:

class Window
{
public:
    const int* GetKeyboard()
    {
        return m_Keyboard;
    }

private:
    const int* const m_Keyboard = 0;
};

With this I would access keyboard as WindowObjectPtr->GetKeyboard() but I want to access it as Input::Keyboard. So I wrote something like this:

class Window
{
public:
    const int* GetKeyboard()
    {
        return m_Keyboard;
    }

private:
    const int* const m_Keyboard = 0;
};

const int* Input::Keyboard = 0;

class Application;
class Input
{
    friend class Application;
private:
    static void SetKeyboard(const int* k) { Keyboard = k; }

public:
    static const int* Keyboard;
};

class Application
{
public:
    void Init()
    {
        Input::SetKeyboard(m_Window.GetKeyboard());
    }

private:
    Window m_Window;
};

int main()
{
    Application application;
    application.Init();

    //Input::Keyboard
}

The only problem with the above code is that I can do Input::Keyboaord = nullptr;

So I want to change definition of keyboard to static const int* const Keyboard; but then Input::SetKeyboard cannot set it anymore.

Is there a valid version of something like mutable static const int* const Keyboard; ? or a different method of achieving what I am trying to do?


Solution

  • Either an object is const or it isn't. If it is const it must be given a value in its initialization and any attempt at changing it later will cause undefined behavior (if it isn't ill-formed to begin with).

    There is no way to make an object const after a certain other point in the execution flow.

    Of course you can just add a const reference to the object and use that whenever you don't intent to modify it for const-correctness:

    static const int* Keyboard;
    static const int* const& cKeyboard = Keyboard;
    

    Now Keyboard can be used for modification and cKeyboard can't (without const_cast trickery).

    But that all seems like completely avoidable and messy, since you could just have Keyboard be a non-static member, have Application have a non-static Input member and then have all initialization happen in the constructor's initializer lists. Then there wouldn't be a problem with having Keyboard be const-qualified at all.