c++constantsogre

C++ Setting member object which has const member


I am using OIS for handling my input with Ogre and currently, on KeyPress/Release a Message object like the following will be constructed and distributed among subscribers.

class Message
{
public:
    Message();
    ~Message();

    inline void SetKeyEvent(const OIS::KeyEvent& keyEvent) { _keyEvent = keyEvent; }

    const OIS::KeyEvent& GetKeyEvent() const { return _keyEvent; }

private:

    OIS::KeyEvent _keyEvent;

};

Since this object will be constructed/destroyed whenever input is received via keyboard, I am trying to store a pre-constructed Message object and then simply update the _keyEvent field with the new data, before distributing.

The problem is that the OIS::KeyEvent object has a const member which is preventing me from using the assignment operator. The SetKeyEvent method gives me the following syntax error:

function "OIS::KeyEvent::operator=(const OIS::KeyEvent &)" (declared implicitly) cannot be referenced -- it is a deleted function

I was wondering what the best way to achieve this functionality would be?

Thanks in advance

EDIT: Just to clarify, I already use initializer lists when possible. My intention is to have the Message object pre-constructed and then update the _keyEvent field with the new event data from the KeyPress event which OIS fires, using the SetKeyEvent method. I would like to know if this is possible and if so, what the best way to do it would be.


Solution

  • The copy operator is deleted, so you must work with pointers.

    class Message
    {
    public:
        Message();
        ~Message();
    
        inline void SetKeyEvent(OIS::KeyEvent* keyEvent) { _keyEvent = keyEvent; }
    
        const OIS::KeyEvent& GetKeyEvent() const { return _keyEvent; }
    
    private:
    
        OIS::KeyEvent* _keyEvent;
    
    };
    

    And now it's better to check if the argument in the setter isn't nullptr.

    inline void SetKeyEvent(OIS::KeyEvent* keyEvent) 
    {
       assert(keyEvent != nullptr);
       _keyEvent = keyEvent; 
    }
    

    assert() needs #include <assert.h>

    EDIT:

    Sorry, forgot the getter method. You must use pointers, too.

    const OIS::KeyEvent* keyEvent = &Message.GetKeyEvent();
    

    Where Message is your class instance.