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
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'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.