Question : how to re-assign a class member in c++ (override its value by pointer)

hello,

i think the title is not very clear. let me explain: say, i have 2 classes by
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:
class B
{
public:
	int BNum;
};

class A
{
public: 
	int ANum;
	B *bMember;
	A(int num)
	{
		ANum = num;
		bMember = new B();
		bMember->BNum = num +10;
	}
	A(B* bb) : bMember(bb)
	{
		ANum = bMember->BNum -20;
	}
	~A()
	{
		delete bMember;
	}
};

and when i create a pointer to A class i can override its ANum member.
1:
2:
3:
4:
5:
6:
7:
8:
9:
int *inta, *intb;
A *aa1 = new A(20);
intb = &aa1->ANum;
inta = new int(100);
*intb = *inta;
cout << aa1->ANum << endl;
cout << *inta << endl;
cout << *intb << endl;

the output is
1:
2:
3:
4:
100
100
100

but things get interesting when i intend to override the b member of class A
1:
2:
3:
4:
5:
6:
7:
8:
9:
10:
11:
B *ba,*bb, *bc;
bc = new B(); bc->BNum = 1000;
A* aa2 = new A(bc);
bb = aa2->bMember;
ba = new B(); ba->BNum = 200;
*bb = *ba;
cout << aa2->ANum << endl;
cout << ba->BNum << endl;
cout << bb->BNum << endl;
cout << bc->BNum << endl;

output :
1:
2:
3:
4:
5:
1000
200
200
200

even the value held by bc changes. but nothing happens to bMember.
the reason for using dummy pointers that, in my application, actually i use vectors of pointers to a field of some type, of my main class. how can i override this field using the pointer contained in my vector. maybe the problem occurs because of my bad design, but i am curious about the situation above. (1000,200,200 ...)
any comments appreciated.
thanks

Answer : how to re-assign a class member in c++ (override its value by pointer)

>> even the value held by bc changes. but nothing happens to bMember.

Of course something happens to bMember : you overwrite it here :

>> *bb = *ba;

bb points to the same B object as aa2->bMember, ie. both point to the object that bc points to.

So, when you dereference the bb pointer (*bb), you get that object (the same object that all the three mentioned pointers point to).
When you then assign *ba to that object, you overwrite it with the new data. This means that all three mentioned pointers will now point to that overwritten object.



I must say though that you're doing some really crazy stuff here. What's the point of all of this code ? It seems highly error prone, and unnecessarily complicated.
Random Solutions  
 
programming4us programming4us