Reputation: 3130
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
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
ret
object is createdret.c_str()
. ret
object make the c-string for you, and return it.ret
is destroyed, and it also destroy c-string, because the owner of that c-string is ret
.Upvotes: 1
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