Objects' initialized variables lose value

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.

Here's the main code block:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
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;
};


Here's InputClass.cpp:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
#include "stdafx.h"
#include "InputClass.h"
#include "resource.h"

InputClass::InputClass(void)
{

}


InputClass::~InputClass(void)
{
}

void InputClass::SetNumber(int _number)
{
	number = _number;
}

void InputClass::Copy(InputClass *ptr2)
{
	ptr2 = this;
}

void InputClass::addNumber(int _number)
{
	number += _number;
}


Here's the InputClass declaration:

Last edited on
Does your InputClass class have a private int variable that has the same name as the one in the Object1 class?

If not, how could you add a member to InputClass? You can't. You can only do it at "global scope" in a class.

Hope this helps,
theturk1234
@theturk1234:
Object 1 (aka inputObject) is an instance of InputClass.
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.
Topic archived. No new replies allowed.