| AngelGithara23 (33) | |||||||
|
Hello, I have two classes that have for member variables pointers to objects of each other like so:
Now It compiles alright but then I get a few runtime errors:
I'm not sure why this happens. Is anyone willing to help me understand the problem and show me a work-around? I'm not really sure how to make it were both classes are dependent on each other, and that's the problem. | |||||||
|
Last edited on
|
|||||||
| helios (10258) | |
| The pointers aren't initialized. | |
|
|
|
| AngelGithara23 (33) | |
|
Thanks for your time helios. EDIT: I've tried tried to initialize the two members in each others constructors to zero, but I'm still getting Access violation errors. I'm looking around on google, but I'm not yet sure how to get this going. | |
|
Last edited on
|
|
| helios (10258) | |
Zero won't do. You have to make them valid pointers by calling the constructor for their objects with new. Example: this->a=new A;I'm looking at your setup, and if you do what I think you're thinking of doing, you'll end up with infinite recursion. | |
|
|
|
| AngelGithara23 (33) | |
|
Yes, I'm getting a stack overflow. I simplified the code in the example a lot, but I'm needing to make the two classes mutually available as members to each other. Are you saying this not possible because I'll get infinite recursion? Should I try to redesign the two classes to have one as the parent and one the dependent? | |
|
|
|
| Disch (8617) | |||
|
EDIT -- blah I totally misread your question. That's what I get for jumping to conclusions. Sorry. ANYWAY, if your goal is to create an A object and a B object which refer to each other, then you can pass 'this' to the other class as the pointer. It's best to have one class be the dominant one, that way cleanup and such is easier
In this example, whenever you create an A object, that A object will in turn create a B object, and they will be "tied" together in the sense that they will point to each other and be able to communicate back and forth. But if you want A to have a B which has another A -- you're starting to step into the world of impossible concepts. After all if A has a B which has another A which has another B which has another A, etc, etc -- you'll end up creating an infinite number of objects. | |||
|
Last edited on
|
|||
| AngelGithara23 (33) | |
|
Thanks Disch. I'll give this a try. EDIT: after giving this a try it seems to work well, I really had no clue what I was doing, thanks. | |
|
Last edited on
|
|