My assignment for this week is to create a class, create an object of that class using the "new" operator, then create two deep copies of the aforementioned object. In my class there is one - and only one - private member, whose value appears to be copying over to the two deep copies. (To confirm this, I have a message box whose code is not shown here) However, before I perform an add operation on that private member, the member loses the previously stored value.
InputClass *inputObj = new InputClass;
int number = GetDlgItemInt(hDlg,IDC_INTINPUT,NULL,NULL);
inputObj->SetNumber(number);
// Make 2 copies of inputObj.
InputClass *inputObj2 = new InputClass;
InputClass *inputObj3 = new InputClass;
inputObj->Copy(inputObj2);
inputObj->Copy(inputObj3);
// Call a method that adds 1 to the private member of the second object.
inputObj2->addNumber(1);
// Call a method that adds 2 to the private member of the third object.
inputObj3->addNumber(2);
// Display the product of the three values in the dialog box.
int product = inputObj->GetNumber() * inputObj2->GetNumber() * inputObj3->GetNumber();
TCHAR productStr[50];
wsprintf(productStr,TEXT("%i"),product);
SetDlgItemText(hDlg,IDC_OUTPUT,productStr);
delete inputObj;
delete inputObj2;
delete inputObj3;
1 2 3 4 5 6 7 8 9 10 11 12
class InputClass
{
public:
InputClass(void);
~InputClass(void);
void Copy(InputClass *);
void SetNumber(int);
void addNumber(int);
int GetNumber();
private:
int number;
};
I found the solution. Use new InputClass(*inputObj) to create deep copies.
Here's why the code didn't work: [code]ptr2 = this[/this] changed the address stored in ptr2 so that ptr2 now points to inputObject. Thus, inputObject2 and inputObject3 did not have their int values changed.