Antimony
Antimony

Reputation: 39451

C++ circular dependency returning by value?

When returning by pointer or reference in C++, it is easy to break circular dependencies with forward declarations. But with do you do in a case where you have to return by value?

Consider the simplified example below

struct Foo {
  Bar bar() {return Bar{*this}; }
};

struct Bar {
  Foo foo;
}

Is there any way to break the circular dependency? Trying to forward declare Bar just leads to a complaint about an incomplete return type.

Upvotes: 4

Views: 407

Answers (1)

MSalters
MSalters

Reputation: 179930

Define the two types, declaring their member functions. Then define the member functions outside the class, and even after the second class definition.

struct Bar;
struct Foo {
  Bar bar();
};

struct Bar {
  Foo foo;
};

Bar Foo::bar() {return Bar{*this}; }

Upvotes: 8

Related Questions