manatttta
manatttta

Reputation: 3130

Overloaded operator returning type

Is it possible to overload an operator returning a string instead of a class type?

string operator++() {
    index++;
    if (index > num_atts) {
        index = 0;
    }

    string ret = att_names[index];
    return ret;

}

Upvotes: 0

Views: 71

Answers (2)

ikh
ikh

Reputation: 10427

That code has no error on syntax. However, it have crucial error on semantic.

const char *operator++() {
    index++;
    if (index > num_atts) {
        index = 0;
    }

    string ret = att_names[index]; // 1
    return ret.c_str();            // 2 & 3
}                                  // 4
  1. The ret object is created
  2. You call ret.c_str(). ret object make the c-string for you, and return it.
  3. Now, you're trying to return the c-string.
  4. But at this time, ret is destroyed, and it also destroy c-string, because the owner of that c-string is ret.
  5. Therefore, now you're returning the destroyed pointer!!

Upvotes: 1

Paul Evans
Paul Evans

Reputation: 27577

You can return any type you like, just like any other function you write. But just like any other function, you can't return a pointer to a local stack variable that's about to go out of scope, that's undefined behaviour. The easiest thing to fix that is to simply return the string, something like:

std::string operator++() {
    // ...
    return ret;
}

Upvotes: 0

Related Questions