Question

I have 2 objects in my code (object 'A' and object 'B'). Firstly, in my main function I create the 'A' object, then inside the 'A' object, I create the 'B' object. Now I want to be able to call some functions and access some class members of one of the classes from the other class. It's easy to access 'B' members from 'A' but I can't do the opposite.

In brief: - From 'A' I want to access some 'B' class members. - From 'B' I want to access some 'A' class members.

My code (this is just a little example to try to explain what I want to do.):

mian.cpp

#include <iostream>
#include "a.h"

using namespace std;

int main()
{
    a *pa;

    pa=new a();

    cout << "Bye" << endl;

    delete pa;

    return 0;
}

a.cpp

#include <iostream>
#include "a.h"

a::a(void)
{
    std::cout << "Class A" << std::endl;
    b_a=new b();

    b_a->fun1(this);
}

void a::fun2(void)
{
    std::cout << "Function 2" << std::endl;
    delete b_a;
}

b.cpp

#include <iostream>
#include "b.h"

b::b(void)
{
    std::cout << "Class B" << std::endl;
}

void b::fun1(a *pa)
{
    std::cout << "Function 1" << std::endl;
    a_b=pa;
    a_b->fun2();
}

a.h

#ifndef A_H_INCLUDED
#define A_H_INCLUDED

#include "b.h"

class a
{
private:
    b *b_a;

public:
    a();
    void fun2();

};

#endif // A_H_INCLUDED

b.h

#ifndef B_H_INCLUDED
#define B_H_INCLUDED

class a; // Forward declaration

class b
{
private:
    a *a_b;

public:
    b();
    void fun1(a *pa);
};

#endif // B_H_INCLUDED

When I try to compile I get this error: "error: invalid use of incomplete type 'class a'". And then: "error: forward declaration of 'class a'".

I guess there's something wrong with forward declaration but I read I had to use it to avoid circular reference in header files.

Any help or suggestion would be really appreciated. Thanks in advance.

Was it helpful?

Solution

In your a.h, do another forward declaration for class b. It's called as circular forward declaration.

http://fw-geekycoder.blogspot.com/2012/04/how-to-resolve-circular-dependencies-in.html

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top