tags:

views:

95

answers:

5

Here is my issue.

I have 2 classes which I want to implement in 1 h file

lets call them class Foo and class Bar. My issue is that Bar has functions which have a return value of Foo and Foo has functions with a return value of Bar.

Therefore, how do I properly forward declare these so they can play nice with each other.

Thanks

+1  A: 

It's fairly easy..

  class A; // yay, forward declared A

  class B {
    private:
      A* fPtrA;
    public:
      void mymethod(const& A) const;
  };

And a more comprehensive guide: http://www.eventhelix.com/RealtimeMantra/HeaderFileIncludePatterns.htm

Which also shows how to handle cyclical dependency:

/* ====== x.h ====== */
// Forward declaration of Y for cyclic dependency
class Y;

class X 
{
    Y *m_y;
    ...
};

/* ====== y.h ====== */
// Forward declaration of X for cyclic dependency
class X;

class Y 
{
    X *m_x;
    ...
};
David Titarenco
A: 

You can't return by value in this situation. You'll have to pass into the function by reference or pointer, and populate that value.

   void stuff(Foo *output)
   {
      //change output;
   }

Or you can return a reference or pointer:

   Foo * stuff()
   {
      return &my_foo;
   }
JoshD
+2  A: 
class Foo;

class Bar{
public:
  Foo * getMyFoo();
private:
  Foo * mMyFoo;
};

class Foo{
public:
  void setMyBar(Bar *);
private:
  Bar * mTheBar;
};
dzada
A: 

Yes you can do what you asked returning by value in both classes

Header

class Foo;

class Bar{
public:
  Foo getMyFoo();
};

class Foo{
public:
  Bar getMyBar();
};

Body

Foo Bar::getMyFoo(){
  return Foo();
}

Bar Foo::getMyBar(){
  return Bar();
}

However, as other have indicated you cannot hold member variable of the other type in each class (you could do it 1 way only) at which point you start to look at pointers and probably shared_ptr and weak_ptr to maintain the relationships and then why would you want to return by value.

Greg Domjan
Can you compile the above code? I had expected that such a thing wouldn't work because `getMyFoo();` doesn't have the full definition of `Foo`.
JoshD
Yes, this compiles.
Greg Domjan
A: 

you can also declare a type within the other type - considering their co-dependence, it is often a good idea.

you can defer instantiation of one interface by using a template.

Justin