//C++ Example
#include
using namespace std;
int doHello (std::string&);
int main() {
std::string str1 = \"perry\";
cout <<
The code you have written in java is equivalent to this C++ code:
int main() {
std::string *s1;
s1 = new std::string("perry");
std::cout << s1->c_str() << std::endl;
doMojo( s1 );
std::cout << s1->c_str() << std::endl; // not pieterson
}
void doMojo( std::string *str ) {
str = new std::string("pieterson");
std::cout << str->c_str() << std::end;
}
perhaps now you see what happens. The C++ references actually wrap around the pointers.. so without the references your code would look like this:
int main() {
std::string *s1;
s1 = new std::string("perry");
std::cout << s1->c_str() << std::endl;
doMojo( s1 );
std::cout << s1->c_str() << std::endl; // now pieterson!
}
void doMojo( std::string *&str ) {
str = new std::string("pieterson");
std::cout << str->c_str() << std::end;
}
notice the innocuous ampersand:
void doMojo( std::string *&str ) {
That really is the secret. This, and the previous answer that explains about immutability of java strings should make you appretiate the difference between java and c++ references.
Cheers,
jrh.