Search code examples
c++arraysconstructorclass-variables

How to pass array to constructor and save in class variable


I have the following peace of code of a Satellite

class Satellite
{
private:
    const static int CHIP_SEQ_LENGTH = 1023;
    bool chipSequence[CHIP_SEQ_LENGTH];
    int id;

public:
    Satellite(int id, bool chipSequence[])
    {
        this->id = id;
        this->chipSequence = chipSequence;
    };
}

I get an error at

this->chipSequence = chipSequence;

with the following description:

Expression must be a modifiable lvalue.

Now my question is, how to store an array passed by the constructor into a class variable?


Solution

  • Built-in arrays are nasty things that don't behave like most C++ objects. In particular, they aren't assignable.

    In modern C++, I'd probably use std::array<bool, CHIP_SEQ_LENGTH>. This is a proper copyable object type.

    If you're stuck in the past, you could make your own copyable wrapper type:

    struct ChipSequence {
        bool bits[CHIP_SEQ_LENGTH];
    };
    

    or explicitly copy the data:

    std::copy(chipSequence, chipSequence+CHIP_SEQ_LENGTH, this->chipSequence);
    

    There are also alternatives like std::bitset or std::vector<bool>, which pack the bits to use less memory, if you don't specifically need an array of bool.