Important: Please read the Qt Code of Conduct - https://forum.qt.io/topic/113070/qt-code-of-conduct

How to overload assignment operator inside a class?



  • Hi! I have a struct that has two members and I want to assign the current value of newState to oldState before changing the value of newState and then emit a signal with the new state as a parameter. My struct looks like this:

    /* myData.h */
    enum class myState_Enum{Uninitialized, OFF, ON, Processing};
    struct myStruct
    {
        myState_Enum oldState,
        myState_Enum newState,
    };
    
    

    The only way I am currently able to override the assignment operator is like this:

    /* myData.h */
    enum class myState_Enum{Uninitialized, OFF, ON, Processing};
    struct myStruct
    {
        myState_Enum oldState,
        myState_Enum newState,
        myStruct &operator=(myStruct val)
        {
            //perform the assignment here
            return *this;
        }
    };
    
    

    But, it defeats the purpose of overloading the assignment operator for me. I want to overload this in my class where this struct is a member so that I can emit a signal each time the newState is changed. I want to do something like this:

    /* mainData.h */
    class mainData
    {
    public:
        mainData();
        myStruct State;
        void operator=(myState_Enum val);
    
    signals:
        void stateChanged(myState_Enum val);
    }
    
    
    /*mainData.cpp */
    mainData::mainData()
    {
        State.oldState = myState_Enum::Uninitialized;
        State.newState = myState_Enum::Uninitialized;
    }
    
    void mainData::operator=(myState_Enum val)
    {
        State.oldState = State.newState;
        State.newState = val;
        emit stateChanged(val);
    }
    

    Is there any way I can achieve this? Thanks :)


  • Lifetime Qt Champion

    Hi,

    Not directly as you want. The usual way is to have a setter that does the value check and emit the signal if appropriate.

    Emitting a signal requires the class to derive from QObject which is not copyable.


  • Lifetime Qt Champion

    Hi,

    Not directly as you want. The usual way is to have a setter that does the value check and emit the signal if appropriate.

    Emitting a signal requires the class to derive from QObject which is not copyable.



  • @SGaist Thank you :)


Log in to reply