Archived

This topic is now archived and is closed to further replies.

__fold

Classes including eachother

Recommended Posts

If I want a class A that can use class B and a class B that can use class A. Then in A.h I include B.h and in B.h I include A.h. Now, this doesn''t work and I understand why. How do I solve this?

Share this post


Link to post
Share on other sites
Either break the dependency between the classes in your design, or use forward declarations in your header files:


A.h:
.
.
class B; // forward declare B

class A {
.
.
void someFunction (const B & b);
};
.
.
B.h:
.
.
class A; // forward declare A

class B {
.
.
void someFunction (const A * a);
};


This only works if your header files has pointers or references of A and B.


--
Dave Mikesell Software & Consulting

Share this post


Link to post
Share on other sites
quote:
Original post by Anonymous Poster


class B;
class A
{
public:
void doSomething(B b);
};

class B
{
private:
A a;
};



This ought to work too.


It will work in the same source file but it won't work the other way. If you want a two classes to each contain an instance of the other you have to user a pointer to that object and dynmaically create it. Like:



class A;

class B {
private:
A *a;
public:
void init(A *aa) { a = aa};
}

then in A's .cpp:

class B;
class A {
private:
B *b;
public:
void init() { b = new B();}
}



[edited by - sagwagon on October 21, 2003 8:28:06 PM]

Share this post


Link to post
Share on other sites
quote:
Original post by dmikesell
Either break the dependency between the classes in your design, or use forward declarations in your header files:


A.h:
.
.
class B; // forward declare B

class A {
.
.
void someFunction (const B & b);
};
.
.
B.h:
.
.
class A; // forward declare A

class B {
.
.
void someFunction (const A * a);
};


This only works if your header files has pointers or references of A and B.


--
Dave Mikesell Software & Consulting


Ahh, I see. I am not the OP but I was making a really cheap text based game (hard-coded with switchs) and couldn''t figure out how I would make it so it could jump around...I got it now!!

Share this post


Link to post
Share on other sites