notsogeek
notsogeek

Reputation: 181

How to solve field 'classname' has incomplete type error

I am getting this error while implementing the following:

class A; class B;

class A {
B b_obj ; //Here comes the error
...
}

class B {
...
A a_object;
...
}

One thing I have observed is that if I shift class B upwards then it gets removed but since I am using two way linking, which also has class A's object in B hence I am not able to get rid of both the errors.

Upvotes: 0

Views: 1120

Answers (2)

user2249683
user2249683

Reputation:

The circular dependency

struct A { B b; }; 
struct B { A a; }; 

will never compile. Either A does not know the size of B or vice versa (One is declared before the other).

Now you could be tempted to write (with forward declarations)

struct A { std::shared_ptr<B> b; }; 
struct B { std::shared_ptr<A> a; }; 

which will compile and (could/would) introduce a memory leak (a refers to b and vice versa).

Hence the question is: Does A own B or B own A - or even another class C owns both.

(Having a defined ownership you might just use new/delete instead of shared_ptr)

Upvotes: 0

Ivan
Ivan

Reputation: 2057

It's called circular dependency problem. See this great answer for details how to solve it.

Upvotes: 1

Related Questions