4

I'm trying to make my own string class in c++11 but I have some problems. comparing my class to the std::string class, I can't figute out how to use the

std::string.at(int) = 'a'; method/overloading.

I've created the at(int) method in my own class:

int at(int index)
{
    if(index <0 || index > size-1) {throw std::out_of_range("Error, index out of range");}
    return data[index];
}

and it workd well if I only use:

MyString.at(2);

In the main file:

MyString = "Hello world!"; //Works fine!
MyString.at(2)='a'; //Gives, Error: expressino must be a modifiable Ivalue.

Any help with this would be great, Thanks!

2
  • Did you look at the documentation for the string class? Commented Oct 19, 2013 at 21:40
  • This is not the problem, but index > size-1 can be written more idiomatically as index >= size. Commented Oct 19, 2013 at 22:22

2 Answers 2

3

At least one of your at() member functions needs to return a non-const reference to char. Like this:

char &at(std::size_t idx)
{
    return data[idx];
}

It would be beneficial to define a const version of the function too:

const char &at(std::size_t idx) const
{
    return data[idx];
}

Also note the use of std::size_t (which is an unsigned type guaranteed to be large enough to represent any size). This way you improve portability and you don't have to check for negative indices.

Sign up to request clarification or add additional context in comments.

4 Comments

It might also be wise to have a const version.
Now I see the obvious problem! Thank you for your help!
@chris Fair enough. Do you mean that the member function itself should be const or the return value should be a reference-to-const char? (The former makes more sense, just checking.)
@H2CO3, Same as the subscripting operator overloads. Both combined.
1

You are returning an integer and not a reference to the character, you probably want:

char& at(int index)

Of course, you need to return the correct character type, but in any case you need to return a reference in order for the caller to be able to assign to it.

1 Comment

Owooo.. how stupid I feel! Thank you for your answer!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.