0

How can I create two different classes that have references to eachother within their code in C++?

It would look something like this;

class A
{
    B b;
}
class B
{
    A a;
}

I get an error on the line of the

B b;

within class A stating;

error: 'B' was not declared in this scope

Rest easy in that I am not declaring a

B b = new B;

in A, nor am I declaring a

A a = new A;

in B, as I'm aware it would cause a StackOverflowException. I will use getters and setters to manipulate the data.

user1973385
  • 145
  • 1
  • 1
  • 8

2 Answers2

1

Use forward declarations, and make the members pointers. It's easiest with two different headers, although it could be done in one:

// A.h
class B;

class A
{
    B* m_pB;
};

And:

// B.h
class A;

class B
{
    A* m_pA;
};

Then #include both headers in each .cpp file (A.cpp and B.cpp).

Dan Korn
  • 1,274
  • 9
  • 14
1

This is probably what you want:

class B;
class A
{
    B* b;
}
class B
{
    A* a;
}

Note that the class B is forward-declared as a class so that the compiler knows what it is when defining A. Also note that A::b is a pointer to B and B::a is a pointer to A (what you probably mean by "reference" if you come from a Java background). If A::b was declared to be of type B and B::a was declared to be of type A then each A object would literally contain an entire B object inside it and vice versa, which I'm guessing is not what you wanted (and is obviously impossible anyway).

Brian Bi
  • 111,498
  • 10
  • 176
  • 312
  • What benefits would come from making the declarations of A and B within class B and A respectively pointers? – user1973385 Feb 12 '15 at 23:43
  • @user1973385 As opposed to what? Like I said, you can't have `A` inside `B` as well as *vice versa*. You could try C++ references (`A&`, `B&`) but that would be... tricky because how would you construct the first one? – Brian Bi Feb 12 '15 at 23:46