tags:

views:

86

answers:

2

Is it possible to define C++ classes Foo and Bar s.t.

class Foo {
  Bar makeBar();
};

class Bar {
  Foo makeFoo();
};

?

Thanks!

+2  A: 

Yes. You can do it with a forward declaration.

For example, in Foo.h, add:

class Bar;

class Foo {
    Bar makeBar();
};
Reed Copsey
Hrm. Why the downvotes?
Reed Copsey
+8  A: 

Yes it is, you just have to put forward declarations at the top.

class Foo;
class Bar;

class Foo {
  Bar makeBar();
};

class Bar {
  Foo makeFoo();
};
Ray Hidayat
How does the compiler know how big Bar is at Foo::makeBar() ?
anon
It doesn't have to know at that point. It just has to know that it's possible to return one. At that point it then constructs the Foo and Bar classes, which now it knows how large they are, and -now- when you call the methods, it has everything it needs. Cool, eh?
Walt Stoneburner
Not for a function declaration. http://www.goingware.com/tips/parameters/notrequired.html
Joel
@anon: It doesn't need to know that as long as this is a mere *declaration* of the function. Incomplete types are OK in the declarations. Once you get to *defining* the functions, the types must be complete. This forces out-of-class function definitions in this case.
AndreyT
It doesn't need to know how big the return value is at declaration time.
Peter