I am studying reference of c++, and now I am quite confused by the difference between variable name and reference. The test code is below:
class TestClass{
private:
int num;
public:
TestClass(int n):num(n){
cout<<this<<" : init of : " <<this->num<<endl;
}
TestClass(const TestClass& t):num(t.num){
cout<<this<<" : copyInit of : " <<this->num<<endl;
}
};
int main(int argc, const char * argv[]){
TestClass t = *(new TestClass(55)); //just to test copy initialization
const TestClass t2 = TestClass(100); //option1
const TestClass &t2 = TestClass(100); //option2
}
So now I have two options in making object, which are exclusive with each other.
In my understanding, if I use options2, the compiler makes a temporary object in the stack memory and returns the reference value to t2.
If this is right, how can I verbalize or explain the option1? It seems that the same object is created in the stack memory and computer gives a name 't2' to that object, but I do not clearly understand how this option1 is different with the option2 because a name of variables and reference are somewhat confusing.
In addition, switching options alternatively, I could see that the objects are created in different memory locations in each case. (e.g. the object of option1 was created in 0x7fff5fbff828, and that or option2 was in 0x7fff5fbff820)
Could you please explain
1. what's the difference between a variable name(option1) and reference(option2).
2. how things work differently in option 1 and 2.
3. why objects are created in different memory location in either cases.
In advance, thanks for your help!