Two classes that calls each other

Started by
2 comments, last by Cornstalks 12 years, 2 months ago
Hi!
I'm trying to compile unsuccessfully a project that has two classes. The class A has class B as a member, and there is a function where send its pointer to class B. I read already a lot of other sites, forum etc an the trick is called Foward Declaration, but seems to not work... Basically the code is this:

#include <stdio.h>
class A
{
public:
B b;
void Init()
{
printf("Init A\n");
b.Init(this);
}
void Ok()
{
printf("OK A!\n");
b.Ok();
}
};
class B
{
public:
A *a;
void Init(A *param)
{
printf("Init B\n");
a = param;
a->Ok();
}
void Ok()
{
printf("OK B!\n");
}
};

int main()
{
A a;
a.Init();
}
Advertisement
Separate declaration and definition.
[source]
class A;

class B
{
public:
A *a;
void Init(A *param);
void Ok();
};

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

void B::Init(A *param)
{
printf("Init B\n");
a = param;
a->Ok();
}

void B::Ok()
{
printf("OK B!\n");
}

void A::Init()
{
printf("Init A\n");
b.Init(this);
}

void A::Ok()
{
printf("OK A!\n");
b.Ok();
}
[/source]
The forward declaration of A is necessary to define the pointer member and parameter in B. The full definition of B is then necessary so that it can be a member of A. Finally, the member functions are defined once all classes are fully defined.
Oh great! So that was the problem, I need to separate the declarations from definitions. Thank you very much, you was clear about the explaining smile.png

Oh great! So that was the problem, I need to separate the declarations from definitions. Thank you very much, you was clear about the explaining smile.png


To expand, one of the reasons you were probably having issues with forward declaration is because forward declaration only really works for pointer types. So if you were trying to forward declare class B before class A, you'll notice class A creates a full B object, not a pointer to a B object, so forward declaration won't solve the problem for that one. You'll have to fully declare class B before class A.

Now on the other hand, class B uses a pointer to an A object, so forward declaring class A before class B will work. That's why BrotherBob switched the order of class A and class B.

But like BrotherBob said, separating the definitions and the declarations is also necessary here, as he's done.
[size=2][ I was ninja'd 71 times before I stopped counting a long time ago ] [ f.k.a. MikeTacular ] [ My Blog ] [ SWFer: Gaplessly looped MP3s in your Flash games ]

This topic is closed to new replies.

Advertisement