Skip to main content
GameDev.net gamedev.net
🔒 Locked

Two classes that calls each other

Started by Xeeynamo Feb 10, 2012 at 6:47 PM 2 replies 1.4k views
Original Post
Xeeynamo
Xeeynamo
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();
}
Brother Bob
Brother Bob
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.
Xeeynamo
Xeeynamo
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
Cornstalks
Cornstalks

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.

Topic Locked

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

Sign in to reply to this topic.