Search code examples
c++stringoperator-overloadingsubclassing

Overloading [] in subclassed C++ string


What is the proper thing for me to return here?

char BCheckString::operator[](int index)
{
    if (index < 0 || this->length() <= index)
    {
        throw IndexOutOfBounds();
        ???Do I need to return something here???
    }
    else
    {
        return ?????;
    }
}

I tried return this[index] but VS2013 says: "no suitable conversion function from "BCheckString" to "char" exists. And I have no idea what to return after the throw.

I have:

class BCheckString : public string
{
private:
    bool checkBounds();
public:
    BCheckString(string initial_string);
    char operator[](int index);
    class IndexOutOfBounds{};
};

and

BCheckString::BCheckString(string initial_string) : string(initial_string)
{
}

char BCheckString::operator[](int index)
{
    if (index < 0 || this->length() <= index)
    {
        //throw IndexOutOfBounds();
        cout << "index out of bounds" << endl;
        return 'A';
    }
    else
    {
        return 'A';
    }
}

Obviously this is homework ;)


Solution

  • While observing that what you're doing here is unnecessary, the syntax is thus:

    return string::operator[](index);
    

    You're calling the operator[] of your string parent. This should be preferred to using c_str because string::operator[] does bounds checking in debug builds.

    It's also worth noting that .at already does bounds checking in release builds, and throws std::out_of_range.

    For the first question, no. After throwing an exception, you don't need to have a return statement. In fact, if you do, the compiler may warn you about "unreachable code".