Connecting classes with pointers

I want two classes to hold a pointer to each other.

C++Builder stops my compile with "files nested too deep" when I try this:

File: test.cpp
#include "a.h"
#include "b.h"

int main(){A a; B b; a.link(&b); b.link(&a); return 0;}

File: a.h
#pragma hdrstop
#include "b.h"
#ifndef A_H
#define A_H
Class A {
  public:
     link(B* b_addr){b_ptr = b_addr;}
  private:
    B* b_ptr;
}
#endif

File: b.h
#pragma hdrstop
#include "a.h"
#ifndef B_H
#define B_H
Class B {
  public:
     link(A* a_addr){a_ptr = a_addr;}
  private:
    A* a_ptr;
}
#endif

I don't want to have to create a superclass over these classes (and thus each class would hold a reference to this superclass and use polymorphic calls.) How can I avoid the recursive header file loading?
}
shadow66Asked:
Who is Participating?
 
chensuConnect With a Mentor Commented:
Replace

#include "b.h"

with

class B;  // forward declaration


Replace

#include "a.h"

with

class A;  // forward declaration
0
 
shadow66Author Commented:
Edited text of question.
0
 
rdfCommented:
include your a.h in your b.h and then you only need to #include your b.h in your main

or if you have a b.cpp, # include a.h and b.h in b.cpp and #include b.cpp in your main

0
 
shadow66Author Commented:
Thanks for the quick response (for so few points...). I'm trying to learn C++ on my own--through books, CDs, etc. Any book recommendations?

Thanks again.
0
 
chensuCommented:
Sorry, I haven't read a C++ study book for a long time. I have been reading some references and documentation.
0
All Courses

From novice to tech pro — start learning today.