Skip to main content
gamedev.net
🔒 Locked

pointers and classes

Started by Ionut Costica 1 reply 250+ views
Original Post
Ionut Costica
Ionut Costica
I have 2 classes, A and B, and i want A to have a child/instance of B, but B know who its father/owner is. For this, I wrote something like the following code (which is really simplified for understanding reasons), but it crashes MS C++.NET. (at run-time)
class A;

class B
{
  friend class A;
  A *owner;
};

class A
{
  friend class B;
  B *child;

  A()
  {
    if(child==NULL) child = new B;
    child->owner = this;
  }
};
 
What could be wrong, and how could I fix it? plz help. 10x.
everything is relative. -- even in the world of computers... so PUSH BEYOND THE LIMITS OF SANITY!
Matt Calabrese
Matt Calabrese
Could be any number of reasons considering you aren't showing the implementation where the crash is occuring.

Most likely the source of your problem is this:


if(child==NULL) child = new B;
child->owner = this;


First off -- since it's in the constructor, checking if the pointer is NULL isn't really getting anywhere. Since it's in the constructor and you never previously initialized the pointer, it's going to be pointing to a garbage location, not necissarily to 0. Checking if it points to nothing is pretty pointless because you know that it's not pointing to anything meaningful yet simply because it's in the constructor and the pointer was never previously initialized.

But the problem is, like I said, that it won't necissarily be pointing to 0 on construction, so the child==NULL comparison isn't meaningful. Not only that, but since

child->owner = this;

is using a pointer that's not pointing to anything meaningful (since it's possible that the if statement was false, though it still executes the line wthout ever dynamically allocating the instance of B), then when you attemp to write data to one of it's members, you may crash the program because that object doesn't actually exist.

[edited by - Matt Calabrese on October 30, 2002 3:26:26 PM]
Ionut Costica
Ionut Costica
10x. that was the error. The constructors were actually more complicated, and I wanted to save some space by using some tricks. looks like the trick was on me... .
everything is relative. -- even in the world of computers... so PUSH BEYOND THE LIMITS OF SANITY!

Topic Locked

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

Sign in to reply to this topic.