Advertisement

C++ Class question

Started by July 26, 2001 09:38 AM
2 comments, last by PSioNiC 23 years, 6 months ago
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?
"This is stupid. I can't believe this! Ok, this time, there really IS a bug in the compiler."... 20 mins pass ..."I'M AN IDIOT!!!"
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.
Advertisement
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.
just a note, still missing the semicolons on that last example by Ruval, but that''s the correct answer.

This topic is closed to new replies.

Advertisement