Search code examples
c++stringclassrecursionreverse

Recursively reversing a string without parameters


I've been given a class smartReverse which contains one member data which is a string called str. I have to implement a member method (without any sort of helper function which takes no parameters and returns the reversed version of str.

This is my attempt so far but this does nothing but send the first character to the end of the string. And from this point I'm pretty clueless. I know how to do this using a helper function but am not allowed to use them here.

string smartReverse::rev_recursive() const
{
        if (str.length() <= 1)
                return str;
        char first_char = str[0];
        smartReverse* remainder = new smartReverse(str.substr(1));
        remainder->rev_recursive();
        return remainder->getString() + first_char;
}

Solution

  • With memleak removed, and using rev_recursive result, the fixed version might be:

    std::string smartReverse::rev_recursive() const
    {
        if (str.length() <= 1) {
            return str;
        }
        char first_char = str[0];
        smartReverse remainder(str.substr(1));
        return remainder.rev_recursive() + first_char;
    }