Field has incomplete type in forward declaration
Solution 1
In this case it's simple enough: since Foo only uses a reference to Bar, flipping them around will do the trick:
class Bar;
class Foo{
public:
void run(int y,Bar& bar);
};
class Bar { ... };
void Foo::run(int y, Bar& bar) {
bar.setx(y);
}
You also need to move the body of Foo::run below, because it's actually using the Bar member function.
Solution 2
Your problem can be reduced to this:
class Foo;
class Bar{
Foo foo_; // error: incomplete type
};
Here you did a forward declaration for type Foo, i.e. a declaration without a complete definition: that's enough in C++ to declare a pointer, but not a concrete instance as you did in Bar.
Either give a complete definition to your class:
class Foo{
// put details here
};
class Bar{
Foo foo_; // OK
};
Or use (smart) pointers, e.g.:
class Foo;
class Bar{
std::unique_ptr<Foo> foo_; // OK
};
Or change order declaration as pointed by Bartek Banachewicz.
beginneR
Updated on June 16, 2022Comments
-
beginneR 11 monthsI reproduce an error with the following simple file.
It says:
field has incomplete type 'Foo'
bar.h:
class Foo; class Bar{ private: int x_; Foo foo_; // error: incomplete type public: void setx(int x) {x_ = x;}; void increment(int); }; class Foo{ public: void run(int y,Bar& bar) {bar.setx(y);}; }; void Bar::increment(int i){foo_.run(i,*this);}Member foo_ must not be a reference or a pointer. The reason for this is that in my actual code, I cannot initialize Foo in the initialization list of Bar.
-
beginneR almost 6 yearswas helpful, thanks! ;)