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.
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}; }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With