If you run the following code it's output is what I would expect to see. If you are to follow the instructions in the comments, which do nothing more than change the MyClass static int variable to an int, the code reacts in a way that is beyond my understanding. Why is it that I must use a static variable to get at the original values of the object passed? I thought the copy constructor "referenced" the orginal object passed, in which case, I should have access to those values. Is this not the case?
I hope that made sense! If not, let me know and I'll try to rephrase.
Code:
// Note: This code is compilable.
#include <iostream>
using namespace std;
class MyClass
{ public:
MyClass(){ cout << "Constructor called and the single member data is initialized to ";}
// Comment out the above line and uncomment the below line.
// MyClass(){ cout << "Constructor called and the single member data is initialized to "; instances = 1;}
MyClass(MyClass &){ cout << "\nCopy Constructor is called and space is pushed onto the ";
cout << "stack for the return value of the function and for the function argument(s)." << endl << endl;
}
~MyClass(){ cout << "Deconstructor Called." << endl << endl; }
static int instances;
// Comment out the above line and uncomment the below line
// int instances;
};
// Comment out the below line.
// After having made the three 'commenting' edits recompile the code.
int MyClass::instances = 1;
int function(MyClass x);
int main()
{
MyClass MyObject;
cout << MyObject.instances << endl;
MyObject.instances = function(MyObject);
cout << "Back in main. The function just returned it's value and set it to MyObject.instances. Which is now ";
cout << MyObject.instances << endl;
return 1;
}
int function(MyClass x)
{
cout << "Now within -function- MyObject has had a shallow(member-wise) copy performed on it. ";
cout << "Thus, x.instances is the only argument that previously got pushed onto the stack. ";
cout << "The value of x.instances is: " << x.instances << endl;
return x.instances;
}