Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 794
Antimony Avatar asked Feb 07 '23 01:02

Antimony


1 Answers

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}; }
like image 100
MSalters Avatar answered Feb 19 '23 10:02

MSalters