Archived

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

PSioNiC

C++ Class question

Recommended Posts

If you have:
  

class FOO {
  public:
    BAR MyBar;
}

class BAR {
  public:
    FOO MyFoo;
}

  
as soon as the compiler hits:
  

BAR MyBar;

  
It will crap out cause class BAR hasn''t been defined yet. Is there some way how I could define my classes at the top kinda like you define functions at the top so that one can call another thats below it in your code?

Share this post


Link to post
Share on other sites
That wouldn''t compile because you are missing semicolons, but assuming you fixed that, it still would not compile because you would create an endless loop of FOOS and BARS. The compiler sees the discrepency and will not compile. It *might* be possible to get the classes to define properly so you could do this, but the program would just crash at that line.

Share this post


Link to post
Share on other sites
You can prototype a class if it''s not actually instantiated before it''s defined, so for your example you couldn''t.

If you did


class Bar;

class FOO
{
public:
BAR *MyBar;
}
class BAR
{
public:
FOO MyFoo;
}

that would be OK, because MyBar is only a pointer to BAR and the compiler doesn''t need to know its size. Your original example, if it compiled, would recursively produce a structure of infinite size.

Share this post


Link to post
Share on other sites