Veky
Veky

Reputation: 53

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.

Upvotes: 5

Views: 364

Answers (2)

Alexey Kukanov
Alexey Kukanov

Reputation: 12784

Another possible way to break the dependency loop is to use a template member function, like this:

struct A {
    template<typename T>  T f() { return T(); }
};

struct B {
    A g() { return A(); }
};

int main() {
    A a;
    B b = a.f<B>();
    A a1 = b.g();
    return 0;
}

It will work for operator() too, though the call syntax will be rather ugly: a.operator()<B>()

Upvotes: 0

cpx
cpx

Reputation: 17567

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; }

Upvotes: 8

Related Questions