Search code examples
c++arraysoverloadingoperator-keywordsubscript

return an array from subscripting operator overload


I'm getting started with c++ and I have this method where I overload the subscript operator "[ ]" but I need to return an array from that method, In the method, I'm trying to return a sub array from a bigger array but I can't seem to return a whole array since I can only return a single element from an array, how can I get the method to return an entire array?

For example:

int& PagedArray::operator [] (int position){
    if(position == 0){
        for(int i = 0; i < 256; i++){
            pageArray[i] = completeArray[i];
            //cout << to_string(i) + " " + to_string(pageArray[i]) << endl;
        }
        return pageArray[0] ;
    }
}

When I try to return I can only get a specific element from the array pageArray, but I need to return pageArray, how can I get that done?

thanks


Solution

  • I need to return an array from that method

    int& PagedArray::operator [] (int position)
    

    The return type that you've given for your function does not match what you need to return. This function returns a reference to an integer; not an array.

    A problem with what you need is that you cannot return an array in C++; that's just not allowed in the language. That is to say, return type cannot be an array. There's a fairly easy way to get around that however: You can return instances of classes and you can store arrays as member of a class. There is a template for such array wrapper class in the standard library. It's called std::array.

    Here is an example of returning a sub-array:

    constexpr std::size_t page_size = 256;
    
    std::array<int, page_size>
    PagedArray::operator[] (int){
        std::array<int, page_size> page;
        std::copy(completeArray, page);
        return page;
    }
    

    Given that you originally tried to return a reference, you may be looking for a way to avoid copying the sub-array by using indirection. A problem is that the sub array doesn't exist anywhere prior to calling the function and you cannot return a reference to something that you create in the function.

    Instead of returning reference to small array, you can return a subrange pointing to the big array. There are actually more than one option in the standard library. There's a general purpose std::ranges::subrange and also std::span that is specific to contiguous ranges. I recommend using the more specific type assuming you aren't templetising the type of the big container. Example:

    std::span<int, page_size>
    PagedArray::operator[] (int){
        return {completeArray, page_size};
    }