class pointer assignment

Started by
7 comments, last by Bregma 16 years, 3 months ago
im having some problems with assigning pointers to class... class A { B* pointer; } A first; first.pointer = new B; A* firstpointer = &A the problem here is that B in "firstpointer" isnt assigned the address of B in "first"... the same here class A { B* pointer; } A first; first.pointer = new B; vector<A*> firstpointer; firstpointer.push_back(&A); how do i fix this? do need to do some "pointer assignment operator"?
Advertisement
I'm not sure to understand your problem. If an object A contains a pointer to another object B, then a pointer to A make you able to reach B just as you do with A itself.

A.Bpointer = new B;
Apointer = &A
then: Apointer->Bpointer == A.Bpointer.

this or I'm missing something...
In your first example, 'firstpointer' points to the object that contains another pointer. So you dereference it twice, as cignox1 said.
The problem is that you do this:

A* firstpointer = &A


when you should actually do this:

A* firstpointer = &first


edit:

However, dereferencing a class should give you compiler errors?
So, is that the code you typed in your program?
Someone who uses a, euhm..., delta!?
its not what ive got in my program.. but its to messy and long to post..

i mistyped.. this is how it should look...

class A
{
B* pointer;
}


A first;
first.pointer = new B;

A* Apointer = &first

vector<A*> vectorApointer;
vectorApointer.push_back(&first);


if i want to call B-> in Apointer i get an memory error...

how does the default assignment operator work with pointers within a class?

and how would i make my own?
I just typed in this program. It ran without any problems.

class B {public:	B():val(5) {}	int val;};class A {public:	B *pointer;};int main() {	A first;	first.pointer = new B;	A *firstpointer = &first;	cout << first.pointer->val << endl;}
hmm... thx... then i guess its something else...

Quote:Original post by Dragon_Strike
the problem here is that B in "firstpointer" isnt assigned the address of B in "first"...


Ummm.... there isn't a B in "firstpointer". It's just a pointer.
Quote:Original post by Dragon_Strike
how does the default assignment operator work with pointers within a class?


The assignment operator for a type pointer to ... works by copying the bits from the source variable to the destination variable. It does not copy the data at the address pointed to by the pointers. It works pretty much like the assignment operator of any garden-variety int type.

If you need to do something special with a pointer variable when copying or assigning an object containing such a beast, you need to implement the copy constructor and assignment operator of your class.

Stephen M. Webb
Professional Free Software Developer

This topic is closed to new replies.

Advertisement