Original Post
Hi! I've run into a problem with two classes that both depend on each other to be defined. Class A can create objects of class B, class B takes a reference to an object of class A in its constructor. Is there any way to declare the classes so that they are aware of each others existence or some other way around this problem? I've attached some sample code below to illustrate my problem: Is anyone able to offer some help? Thanks in advance!
//Declarations (that do not work)
class A;
class B;
//Definition of class A
class A {
protected:
~A() {
if(m_b != NULL) {
m_b->Release();
m_b = NULL;
}
}
public:
A() : m_iRefs(0), m_b(NULL) { };
void CreateB(B**_b) {
*_b = new B(*this);
(*_b)->AddRef();
this->AddRef();
if(m_b != NULL) {
m_b->Release();
m_b = NULL;
}
m_b = *_b;
m_b->AddRef();
};
void AddRef() { m_iRefs++; }
void Release() {
if(--m_iRefs <= 0) {
delete this;
}
};
private:
unsigned int m_iRefs;
B *m_b;
}
//Definition of class B
class B {
protected:
~B() {
m_a.Release();
}
public:
B(A &_a) : m_iRefs(0), m_a(_a) { };
void AddRef() { m_iRefs++; }
void Release() {
if(--m_iRefs <= 0) {
delete this;
}
};
private:
unsigned int m_iRefs;
A &m_a;
}
int main() {
A *a = new A();
B *b = NULL;
a->CreateB(&b);
b->Release();
a->Release();
}