The interface of your function assumes that the function dynamically creates a string and returns it to the user of the function. The owner of the pointer is the code that called the function. This calling code is responsible for destroying the string it received from the function if it is useless.
Another thing is that the function is written, let's say, not in the best style.
First, since this function appears to be a member function of the class, and it does not change the class object itself, it is better to declare it with the const qualifier.
It is also not clear what the magic number 32 means. If this is a space code in the ASCII character table, then it is better to write a space character instead of the given magic number. If this is not the case, then it is better to enter the mnemonic name for this literal so that it has some meaning for the reader of your code.
In your function, the function std::strlen is called three times.
The function might look like this.
char * operator-() const { size_t n = std::strlen( str ); char *new_str = new char[ n + 1 ]; for ( size_t i = 0; i < n; i++ ) { if ( str_[i] != ' ' ) new_str[i] = str_[i] - ' '; else new_str[i] = str_[i]; } new_str[n] = '\0'; return new_str; }
Please note that it would be a mistake to use this function as follows.
std::cout << -obj;
Where obj is an object of the class where this operator is defined. In this case, the pointer returned from the function will be lost. You should first assign it to some variable. for example
const char *s = -pbj; std::cout << -obj; delete [] s;
To avoid problems of this kind, it is better to use the standard class std::string instead of pointers to character arrays.
In this case, the function definition might look like this.
#include <string> //... std::string operator-() const { size_t n = std::strlen( str ); std::string new_str( n, ' ' ); for ( size_t i = 0; i < n; i++ ) { if ( str_[i] != ' ' ) new_str[i] = str_[i] - ' '; else new_str[i] = str_[i]; } return new_str; }
And then you can, without fear of memory leaks, write
std::cout << -obj;
Also consider the option when the operator returns not just a string, but an object of your own class. For example,
String operator-() const;
Then, since, as I suppose, the class has an appropriate destructor, you can also feel free to write
std::cout << -obj;
provided that you have defined the operator << output statement for your class.
deleteis not needed here, since you are returningnew_str. Is there anywhere else - you know better, the local telepaths went on vacation yesterday :) - PinkTux