Search code examples
c++arraysoperator-overloadingassignment-operatorc++98

C++ operator = for arrays with class member function


I have a wrapper data structure that I'd like to write a method for the copy assignment operator. I'd really like to do this (because my byte_array can do some really cool stuff):

byte_array bytes = {0x00, 0xAB, 0xEE, 0xFF};

and the function I'm trying to write looks like this so far:

template <int N>
byte_array& byte_array::operator = (const unsigned char (&a)[N]) {
    if(N <= capacity) { //capacity is a class field
        for(int i = 0; i < N; i++) array[i] = a[i]; //array is a class field
        usage = N; //usage is a class field
    }
    return *this;
}

However, this code doesn't compile, as it does not like that I gave it a list. It doesn't like a lot of things about this.

Is there something wrong with the function I wrote, such as the assignment operator only working on objects of the same type (like a conflict of byte_array and unsigned char[])? Is it an issue of my 'list' that I'm trying to assign it to not matching up with the unsigned char[] type?

I was basing my function off of an answer to this past question about arrays in C++.


Solution

  • The issue with

    byte_array bytes = {0x00, 0xAB, 0xEE, 0xFF};
    

    is that you you do not actually have an array on the right hand side. You have an initializer list, which doesn't have a type.

    What you can do though is take a std::initializer_list<unsigned char> and that can be constructed from the initializer list.

    In C++98 you can create a temporary array and then use that array from the assignemnt like

    byte_array bytes;
    //some code
    {
        unsigned char temp[] = {0x00, 0xAB, 0xEE, 0xFF};
        bytes = temp;
    }
    // more code
    

    Also note that Type name = initializer; is never assignment. It is called copy initialization/copy list initialization(if initializer is a initializer list), and calls the copy/move constructor of the object. The assignment operator is only ever called then you have an already constructed object.