0

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.

notsogeek
  • 181
  • 2
  • 13
  • 4
    You want `A` to contain a `B` and `B` to contain an `A`? That's impossible. At least one will have to be a reference or pointer. – Mike Seymour Oct 08 '13 at 16:56
  • I'm afraid you'll have to rethink your design; there's no way to get around a circular dependence of that sort. Maybe one of the classes can hold a pointer to the other? – Praetorian Oct 08 '13 at 16:57
  • So why does the problem solves as for A a_object (no error there) – notsogeek Oct 08 '13 at 17:07
  • 1
    You may want to be clearer on the problem you're trying to solve, not the problem in your code, which Mike has quite-accurately described. If `A` is to contain a `B`, and `B` is to contain a *reference* or *pointer* to it's "owning" `A`, (or vice-versa), you may wish to bring that as clarity. This is highly likely an XY problem. – WhozCraig Oct 08 '13 at 17:36

2 Answers2

1

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

Community
  • 1
  • 1
Ivan
  • 2,007
  • 11
  • 15
  • No I have tried keeping in different files but that further leads to situation(error:nested includes) that I have to add A.h to C.cpp and B.cpp , further B.h to A.cpp and C.cpp and so on.That didn't work. – notsogeek Oct 08 '13 at 17:04
  • @notsogeek, have you read that answer? Again, there is a real working solution. Read it carefully. – Ivan Oct 08 '13 at 17:58
0

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)