how can two class reference each other?

From: cppaddict (
Date: 10/15/03

Date: Wed, 15 Oct 2003 00:58:45 GMT


Is it possible that class A references class B, and class B references class

Specifically, here is my problem. I have a card table class (Table), which
a table at which players might play blackjack or some other game. I also
have a Hand
class, which represents the various hands being played at the table. Thus
Table has
a member which is a list of Hand objects. However, it will sometimes be
convenient for
a Hand object to have a reference to the Table which contains it: eg, a
blackjack hand
might need to split itself, which would involve adding a new Hand to the
Table's list
of hands. So I thought I could make a Table& one of the members of Hand.
But now
the compiler has a chicken and egg problem: It has to compile one class
first, but whichever
class it does try to compile first will reference the other class, which is
not yet defined.

I think that either:

1. There is some general design pattern I should be using instead of
referencing a containing
object, and that this patter would solve my problem better.

2. There is some way to make this work.

Does anyone know?


In case the above description isn't clear enough, here is my (impossible to
compile) code:

#include "stdafx.h"
#include <string>
#include <algorithm>
#include <list>
using namespace std;

class Table {
 list<Hand> m_hands;
 void addHand(Hand h) {m_hands.push_back(h);}
 void showHands() {
  list<Hand>::iterator iter;
  for (iter = m_hands.begin(); iter != m_hands.end(); iter++)

class Hand {
 int m_card1;
 int m_card2;
 Table& m_table;
 void show() {cout << m_card1 << " " << m_card2 << endl;}
 void setCards(int i) {m_card1 = i; m_card2 = i;}
 int getCard1() {return m_card1;}
 void split() {m_table.addHand(*this);}

int main() {
 Table myTable;
 Hand myHand;
 return 0;