When you have a function that returns a reference to a private member in a class, I noticed it compiles fine without explicitly creating a reference to said member of class.
If I do, for example:
Code:
#include <iostream>
#include <string>
using namespace std;
class aClass {
public:
const string& returnString();
private:
string exampleStr;
};
const string& aClass::returnString() {
exampleStr = "anExampleStr";
return exampleStr;
}
int main() {
aClass object;
cout<< "Example string is: " << object.returnString() <<endl;
cout<< "\n\nPress Enter to end this program." <<endl;
cin.get();
return 0;
}
and return a string and not actually a reference (at least not a reference explicitly defined), it will still compile and give me the content of the exampleStr. Why is that?
Why don't I have to do this:
Code:
#include <iostream>
#include <string>
using namespace std;
class aClass {
public:
const string& returnString();
private:
string exampleStr;
};
const string& aClass::returnString() {
exampleStr = "anExampleStr";
const string& rExampleStr = exampleStr; //get a reference to the string member
return rExampleStr; //return the reference
}
int main() {
aClass object;
cout<< "Example string is: " << object.returnString() <<endl;
cout<< "\n\nPress Enter to end this program." <<endl;
cin.get();
return 0;
}
and explicitly return a reference to the private string member?