Skip to main content
GameDev.net gamedev.net
🔒 Locked 🎮 Unity

pointer to class

Started by daniel_i_l Apr 6, 2006 at 4:41 PM 1 replies 400+ views
Original Post
daniel_i_l
daniel_i_l
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.
"We've all heard that a million monkeys banging on a million typewriters will eventually reproduce the entire works of Shakespeare. Now, thanks to the internet, we know this is not true." -- Professor Robert Silensky
RaptorZero
RaptorZero
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]
error C2065: 'signature' : undeclared identifier
Doggan
Doggan
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);}

Topic Locked

This topic has been locked by a moderator. New replies are not allowed.

Sign in to reply to this topic.