• Advertisement
Sign in to follow this  

pointer to class

This topic is 4340 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

If I have two class like this:
class B;
class A{
public: 
 int x, x_squared;
 B* p_toB;
void Update(){x_squared = p_toB->pow2();}
};

class B{
public:
 A* p_toA;
 int pow2(){return(p_toA->x*p_toA->x);}
};

A var_A;
var_A.x=10;
var_A.Update();

will var_A.x_squared = 100; ? I know that this seems like a silly question but it represents a much more complicted case. Thanks.

Share this post


Link to post
Share on other sites
Advertisement
No, because p_toB (inside A) is a pointer wich doesn't point to anything meaningfull (because it hasn't been initialized).

First thing you should do like:
var_A.p_toB = new B;

Or:
B var_B;
var_A.p_toB = var_B;

Both before calling var_A.Update(), otherwise it would probably crash.

[Edited by - RaptorZero on April 6, 2006 5:52:12 PM]

Share this post


Link to post
Share on other sites
Assuming you initialize p_toB and p_toA (as the above poster mentioned)... Then the answer is: not necessarily.

You are creating a class of type A on the stack with this call:

A var_A;
var_A.x=10;
var_A.Update();


var_A contains a pointer to a class of type B (called p_toB). But p_toB->p_toA is not necessarily pointing back to var_A (and most likely it isn't, unless you specifically set it). p_toB->p_toA is some totally different A class, whose x values hasn't been set to anything.

Assuming you new p_toB and p_toA in your constructors, and set all variables to 0, var_A.x_squared will be 0 after those calls.


Edit: Upon further consideration, you can't 'new' p_toB in A() and 'new' p_toA in B() or you will get an infinite loop syndrome and an ugly crash. So, one of those classes must be created in a different area and the pointer must be sent to the class that requires it.

Edit2: This will give you your 100:


A::A() {
x = x_squared = 0; p_toB = new B;
}

B::B() {}

void A::Update(){
x_squared = p_toB->pow2( this );
}

int B::pow2( A *aPtr ){
return(aPtr->x*aPtr->x);
}

Share this post


Link to post
Share on other sites
Sign in to follow this  

  • Advertisement