Skip to main content
gamedev.net
🔒 Locked

Recursive Includes

Started by jonbell 5 replies 300+ views
Original Post
jonbell
jonbell
I have 2 classes which will use each other. Class A will call a function of class B and pass a ''this'' pointer to allow class B to get what it needs from A. The problem is that in the header files now i have class A including b.h and class B including a.h The compiler doesn''t like this, I think because it is causing some kind of recursive include problem. How do i work around this?
malpass
malpass
bin a while since i''v done C++ but you could use friend bridges


  
#include <iostream.h>

class alpha
{
friend class beta;
int aVar;
beta* bp1;

public:
alpha();
~alpha();
void aFunc();
void display();
};
class beta
{
friend class alpha;
int bVar;
alpha* ap1;

public:
beta(alpha* ap) : ap1(ap) {}
void bFunc()
{
ap1->aVar = 3;
}
};

alpha::alpha()
{
bp1 = new beta(this);
cout << "Created bp1\n";
}
alpha::~alpha()
{
delete bp1;
cout << "Deleted bp1\n";
}
void alpha::aFunc()
{
bp1->bVar = 7;
}
void alpha::display()
{
cout << "Alpha''s Friend Beta Var Is: " << bp1->bVar << endl;
}

void main()
{
alpha a1;
a1.aFunc();
a1.display();
}
Dire.Wolf
Dire.Wolf
Do this:



// ----------------------------------------
//
// file: A.h
//
// ----------------------------------------

class A
{
public:
...
};

// ----------------------------------------
//
// file: B.h
//
// ----------------------------------------

class A; // forward declare class A

class B
{
public:
SomeFunction(A& ref);
SetParent(A& ref);

private:
A* parent_;
};



File B.h no longer needs to include A.h due to the forward declaration of class A before the declaration of class B. This works because the compiler doesn't need a definition for reference types. This technique works for both member variables and method parameter declarations.

This is a very common technique to reduce header dependencies as well as being necessary in situations such as yours. It is important to note that forward declarations only work when the object is passed/held by reference (either pointer or reference.)

Hope this helps.



[edited by - Digitalfiend on April 27, 2003 10:25:42 AM]
[email=direwolf@digitalfiends.com]Dire Wolf[/email]
www.digitalfiends.com
jonbell
jonbell
No same error :

error C2027: use of undefined type ''Class B''

The reason is deffinitly becuase A is including b.h and B is including a.h


jonbell
jonbell
Sorry the above post came while i was replying. The problem was that i wasn''t using a refernce. Thx .

Topic Locked

This topic has been locked by a moderator. New replies are not allowed.

Sign in to reply to this topic.