Why does this:
#include
#include
using namespace std;
class Sandbox
{
public:
Sandbox(const string& n) : member(n) {
Here's the simplest way to explain what happened:
In main() you created a string and passed it into the constructor. This string instance only existed within the constructor. Inside the constructor, you assigned member to point directly to this instance. When when scope left the constructor, the string instance was destroyed, and member then pointed to a string object that no longer existed. Having Sandbox.member point to a reference outside its scope will not hold those external instances in scope.
If you want to fix your program to display the behavior you desire, make the following changes:
int main()
{
string temp = string("four");
Sandbox sandbox(temp);
cout << sandbox.member << endl;
return 0;
}
Now temp will pass out of scope at the end of main() instead of at the end of the constructor. However, this is bad practice. Your member variable should never be a reference to a variable that exists outside of the instance. In practice, you never know when that variable will go out of scope.
What I recommend is to define Sandbox.member as a const string member;
This will copy the temporary parameter's data into the member variable instead of assigning the member variable as the temporary parameter itself.