Overflowh
Overflowh

Reputation: 1114

Subscript operator overloading: returning reference problems

I'm overloading the subscript operator for the first time and I'm having troubles in returning a reference value.
I followed the rules of thumb from a post in c++faq tag, but there's something I'm missing.

const T& operator[](int index) const {
    if ((index < 0) || (index > size)) {
                    // provide exception handling for this error
        std::cout << "Error! Index out of bound." << std::endl;
        std::exit(0);
    } else {
        Block* b = head;
        while (b) {
            if (b->position == index)
                return *b->data;

            b = b->next;
        }
    }
}

I implemented them in both variants: with const return value and const function (as above), and without (that is identical except for the two const keywords).
The problem is that when I run the test main, it simply crashes. I thought that the bug was in the return *b->data; statement, but I can't figure neither which it could be nor if I'm wrong and there are other errors.
Any ideas?
Thanks in advance.

Upvotes: 0

Views: 1526

Answers (1)

Nic007
Nic007

Reputation: 634

If you want to return a reference on data, I'm not sure if it's what you want, you to return a reference of type T and I'm assuming data is of type T, it should be something like:

return b->data;

Else, you are returning a reference on the adress of data.

EDIT: Corrected a mistake

Upvotes: 1

Related Questions