user2967799
user2967799

Reputation: 237

How do you use a copy constructor to copy over constant variables?

My class has the following private variables, including a const static one, as you can see:

private:
    // class constant for # of bits in an unsigned short int:
    const static int _USI_BITS = sizeof(usi)*CHAR_BIT; 
    usi* _booArr;  
    int _booArrLen;
    int _numBoos;

I'm new to using copy constructors and I can't figure out how to write one. Here's my attempt:

BitPack::BitPack(const BitPack& other) { 
    _USI_BITS = other._USI_BITS;
    _booArr = new usi[other._booArrLen];
    for (int i = 0; i < _booArrLen; ++i)  
        _booArr[i] = other._booArr[i];
    _booArrLen = other._booArrLen;
    _numBoos = other.numBoos; 
}

The compiler says:

error: assignment of read-only variable 'BitPack::_USI_BITS'

Please disabuse me of my foolish ways.

Upvotes: 1

Views: 400

Answers (1)

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 726569

Constructors, including the copy constructors, need to set instance members, i.e. the ones that are not static. Static members are shared by all instances, and therefore must be initialized outside of any constructors.

In your case, you need to remove the

_USI_BITS = other._USI_BITS;

line: the two sides refer to the same static member, so the assignment has no effect.

The rest of your copy constructor is fine. Note that since your copy constructor allocates resources, the rule of three suggests that you should add a custom assignment operator, and a custom destructor:

BitPack& operator=(const BitPack& other) {
    ...
}
~BitPack() {
    ...
}

Upvotes: 1

Related Questions