Pointer doesn't show changes from another class

I don't understand why the pointer doesn't get reflected back to main when storing it and changing it in Class2. It's still 5 when it should be 9. WTF is going on???

main.cpp:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
int main(int argc, char **argv)
{
	Class1 *C1 = new Class1();
	C1->value = 5;

	printf("Initial value of C1: %d\n", C1->value);

	Class2 C2;
	C2.Initialize(C1);
	C2.PerformAction();

	printf("Subsequent value of C1: %d\n", C1->value);

	getchar();
}


class1.h:
1
2
3
4
5
6
7
8
9
10
11
12
#ifndef CLASS1_H
#define CLASS1_H

class Class1{

public:
	Class1(){}
	~Class1(){}
	int value;
};

#endif 


class2.h:
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
#ifndef CLASS2_H
#define CLASS2_H

#include "class1.h"

class Class2{

public:
	Class2(){}
	~Class2(){}
	void Initialize(Class1 *_C1)
	{
		C1 = _C1;
	}

	void PerformAction()
	{
		Class1* C1N = new Class1();
		C1N->value = 9;

		C1 = C1N;
	}


	Class1 *C1;
};

#endif 
Last edited on
Pointers are just variables that hold addresses.
In PerformAction you're assigning the address of a new Class1 instance to the member pointer C1.
The pointer variable C1 in main is an entirely different variable and therefore isn't affected. It'll still point to the other Class1 instance.
What I wanted was to save the pointer from main in C2 and have the stuff I do in C2 also show up in the object in main since there would be a common pointer to where it is in memory. But apparently the C1 ptr in Class2 is a new separate pointer instead of sharing the one in main.
You could make it a reference to a pointer:
void Initialize(Class1 *&_C1)
You're confusing pointers with addresses.
A pointer is a variable that can store addresses, just like an int variable can store integers.
new returns an address to a newly created object, which you're assigning to the pointer C1 in main.
You store a copy of that address in a member of C2. Both pointers now point to the same object, but you're assigning a new address to the member pointer in PerformAction, so it now points to a different object, while the pointer in main still points to the old object.
Thanks L B, that worked. I just had to make these changes to Class2:

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
#ifndef CLASS2_H
#define CLASS2_H

#include "class1.h"

class Class2{

public:
	Class2(){}
	~Class2(){}
	void Initialize(Class1 *& _C1)
	{
		C1 = &_C1;
	}

	void PerformAction()
	{
		Class1* C1N = new Class1();
		C1N->value = 9;

		*C1 = C1N;
	}

	Class1 **C1;
};

#endif 
Last edited on
Topic archived. No new replies allowed.