C++ - overloading [] operator
Asked Answered
P

3

26

I have a template class Array:

template <class T=int, int SIZE=10>
class Array {
    T TheArray[SIZE];
public:
    void Initialize() {
        for (int idx=0; idx < SIZE; idx++) {
            TheArray[idx] = T();
        }
    }

    T& operator [](int idx) {
        return TheArray[idx];
    }

    T operator [](int idx) const {
        return TheArray[idx];
    }
}

I have some questions on operator [] overloading (I found this example on net).

I understand that T& operator [](int idx) returns a reference to an array value with index idx and that T operator [](int idx) const returns its value. However, I am not sure in which case a reference or a value will be returned by using the [] operator.

Also, if I change T operator [](int idx) const -> T operator [](int idx), the compiler complains. Why is that? I can understand that the compiler complains because only the return type is different, but why doesn't it complain when const is added? This only means that none of the class internals are modified, right?

I tried to debug this small main implementation:

int main() {
    int val;
    Array<> intArray;

    intArray.Initialize();
    val = intArray[1];
    printf("%d", intArray[1]);
    intArray[1] = 5;
}

And each time T& operator [](int idx) is called. Why?

Thanks in advance.

Protrusile answered 4/1, 2016 at 14:22 Comment(1)
On a side note, prefer proper constructors to functions like initialize. C++ gives you a perfect tool for objects initialization, and it's called a constructor.Mayda
C
26

The operator[] overload will be selected based on the const-qualification of the object you call it on.

Array<> intArray;
intArray[1]; //calls T& operator[]

const Array<> constArray;
constArray[1]; //calls T operator[]

If you remove the const from T operator[], you get an error because the member functions cannot have the same const-qualification and parameters as there would be no way to select between them.

Customary answered 4/1, 2016 at 14:28 Comment(0)
A
15

First thing, regard [] as syntactic sugar for calling this->operator[].

The const version will be called if this is a const pointer, else the non-const version will be called.

Moving on, you ought to use const T& operator [](int idx) const {, i.e. have the const version return a const reference. That will save the overhead of taking a deep copy.

Finally, the const-ness of a function is part of its signature. This allows you to overload based on const-ness. Otherwise you couldn't have the two versions of operator[].

Angieangil answered 4/1, 2016 at 14:29 Comment(1)
I'd even call returning a temporary instead of const reference a design smell/bug here, as it leads to inconsistencies, i.e: why cant I use const arguments in memcpy? One should orient itself on the standard library to prevent surprising behaviour and std::vector returns a const reference.Atilt
A
0

I wish to add the following precision : The [] is used to achieve two things : The first one is to get the contents in which case you return the value, and you need a const method to ensure that the value is not modified.

The method which returns a reference is used when you assign a value, which implies that you cannot make it const. Returning a reference enables to modify the actual value, not a copy of it

Assurance answered 7/6 at 7:41 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.