Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mutual return types of member functions (C++)

Is it possible in C++ to have two classes, let's call them A and B, such that A has a member function f that returns an object of class B, and B has a member function g that returns an object of class A?

(The text below is just to show I have "done my homework".)

The problem is just how to write signatures of these functions, when the one in first defined class will have an incomplete return type. Forward declarations don't help here, because objects are returned by value.

Yes, I know all the workarounds (friend global functions, returning by pointer,...), but I would just like to know if the interface as above can be implemented in C++. For the sake of an example, let's say that I am trying to overload operator() on class A to return B, and on class B to return A. Since I am overloading operators, I must return by value (well, unless I want a dynamic allocation hell:), and () must be overloaded as a member function, so I can't use global friends.

like image 393
Veky Avatar asked May 21 '11 05:05

Veky


1 Answers

Yes, Implement function definitions of class A after you declared class B

class B;

class A
{
    B f();
};

class B
{
    A g() { A a; return a; }
};

B A::f(){ B b; return b; }
like image 97
cpx Avatar answered Sep 27 '22 21:09

cpx