Link to home
Start Free TrialLog in
Avatar of hbean
hbean

asked on

Object Problem...(newbie stuff)...

Afternoon all...

Im trying to create a class like such:

class Node{
...
Root *root;
...
}

class Root{
...
Node *node;//actually a vector, but none the less..
...
}

The compiler wont let me place a pointer to root into my node object because root hasnt been declared yet...and if I switch the order the problem will be just the opposite.  Is this an impossiblity w/ C++?  (I'm an experience Java programmer, new to c/c++).

Thanks!
-hhb
ASKER CERTIFIED SOLUTION
Avatar of Kent Olsen
Kent Olsen
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
One of the things about C, C++, PASCAL and a lot of other languages is that you can only create references to objects that the compiler knows about.  (Personally, I'd prefer that the compiler resolves some of this later.  After all, a pointer to a class takes up exactly the same space as a pointer to an int so it's not a matter of the type of object being indefinite.)

But I digress.


For complex types (struct, typedef struct, and class) it is often desireable to have links in both directions.  But as you've discovered, the compiler won't let you define have a pointer to an object for which it has no definition.

Hence, the forward reference.

class Second;

class First
{
  Second *SecondPtr;
};

class Second
{
  First *FirstPtr;
}


Good Luck,
Kent
Avatar of hbean
hbean

ASKER

Awesome.  I knew it was easy LOL.  Thanks!