• Advertisement
Sign in to follow this  

Two classes that calls each other

This topic is 2173 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

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();
}

Share this post


Link to post
Share on other sites
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.

Share this post


Link to post
Share on other sites
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

Share this post


Link to post
Share on other sites

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.

Share this post


Link to post
Share on other sites
Sign in to follow this  

  • Advertisement