Archived

This topic is now archived and is closed to further replies.

A REALLY easy classes question

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

Recommended Posts

I have 2 classes - A and B, and class A has a pointer to an object of class B, and vice versa. However, when I try and compile, obviously the compiler doesn''t recognise the class B pointer in class A as class B hasn''t yet been defined. The question is, how do I do this? Any help would be much appreciated. Here''s the source
  class A { B * Bp; }; class B { A * Ap; }; 
http://www.geocities.com/ben32768

Share on other sites

Prototypes!
  class a;class b;class a{b* lpb;};class b{};

Share on other sites
quote:
Original post by benjamin bunny

I have 2 classes - A and B, and class A has a pointer to an object of class B, and vice versa. However, when I try and compile, obviously the compiler doesn''t recognise the class B pointer in class A as class B hasn''t yet been defined. The question is, how do I do this? Any help would be much appreciated.

Here''s the source

  //// Forward reference here.//class B; class A{ B * Bp; };class B{ A * Ap;};

http://www.geocities.com/ben32768

YAP YFIO,

Share on other sites
Use class prototypes. You can do this because the second class isn''t used in class A''s declaration.

--:
class B;

class A
{
B * Bp;
};

class B
{
A * Ap;
};

--:
Note: if class A were declared as:
class A
{
B aB;
};

it wouldn''t work, since B hasn''t been declared, so the compiler won''t know the size of B, and will be unable to allocate space for the B member of class A.

Dark Lord Pi

Share on other sites
I did wonder if you could do that, but when I tried it last it crashed, so I assumed you couldn''t. Probably a problem somewhere else in my code. Anyway, thanks for the responses.

http://www.geocities.com/ben32768

• 23
• 10
• 19
• 15
• 14