Dan Dv
Dan Dv

Reputation: 493

reference and const reference returned from operator in C++

I do not understand why we usually need two versions of functions that return reference - one const and the other not. For example in this code:

const char& String::operator[](int index) const {
    verify_index(index);
    return data[index];
}

char& String::operator[](int index) {
    verify_index(index);
    return data[index];
}

if we only had const, then we wouldn't be able to do for example str[i] = value. But what is the problem with only having non-const reference, can someone please give an example?

Thanks

Upvotes: 2

Views: 123

Answers (3)

IronMensan
IronMensan

Reputation: 6831

There are two instances of the const keyword in your example and you seem to be ignoring the second one, the one that allows you to call the operator on a const instance.

Upvotes: 0

Mooing Duck
Mooing Duck

Reputation: 66922

If you only had a nonconst overload, you would be unable to use the [] synax on const strings.

void print_first(const std::string& word) {
    std::cout << word[0]; //like this
}

If you have only the const overload, you would be unable to use the [] syntax to modify the string:

void edit_first(std::string& word) {
    word[0] = 'a';
}

If you made a const overload that returns a mutable char, that's even worse!

void edit_first(const std::string& word) {
    word[0] = 'a'; //wait, I thought word was const?
}

It's a frustration that you have to add two overloads, but usually 90% of the code can be shared (as you did with verify_index), or they end up being just two-liners.

(There is a fourth combination of a nonconst overload that returns a const char, but that's harmless and mostly useless so... yeah.)

Upvotes: 3

Bartek Banachewicz
Bartek Banachewicz

Reputation: 39380

const String s = "abc";

cout << s[0]; // Ooops! Cannot run operator[] because no const qualifier.

Upvotes: 1

Related Questions