Allow member to be const while still supporting operator= on the class

Posted by LeopardSkinPillBoxHat on Stack Overflow See other posts from Stack Overflow or by LeopardSkinPillBoxHat
Published on 2010-04-12T06:50:05Z Indexed on 2010/04/12 6:53 UTC
Read the original article Hit count: 368

Filed under:
|
|

I have several members in my class which are const and can therefore only be initialised via the initialiser list like so:

class MyItemT
{
public:
    MyItemT(const MyPacketT& aMyPacket, const MyInfoT& aMyInfo)
        : mMyPacket(aMyPacket),
          mMyInfo(aMyInfo)
    {
    }

private:
    const MyPacketT mMyPacket;
    const MyInfoT mMyInfo;
};

My class can be used in some of our internally defined container classes (e.g. vectors), and these containers require that operator= is defined in the class.

Of course, my operator= needs to do something like this:

MyItemT&
MyItemT::operator=(const MyItemT& other)
{
    mMyPacket = other.mPacket;
    mMyInfo = other.mMyInfo;
    return *this;
}

which of course doesn't work because mMyPacket and mMyInfo are const members.

Other than making these members non-const (which I don't want to do), any ideas about how I could fix this?

© Stack Overflow or respective owner

Related posts about c++

Related posts about operators