Problem when two classes use each other!

In the following code class A has a method witch has a parameter an object of class B. Class B has also a method with a parameter an object of class A.
The program does not compile. The foreword declarations of the two classes didn't help! I understand the reason but I don't know how to solve it!
Any help is welcome. If you propose a solution, please give a working version of my code as well.

Thanks a lot!

#include <iostream>
using namespace std;

class A;
class B;

class A
{
public:
int A1;
void display(B objB)
{
cout<<objB.B1<<endl;
}

};

class B
{
public:
int B1;
void display(A objA)
{
cout<<objA.A1<<endl;
}

};

int main()
{
A Aobj;
B Bobj;
Aobj.A1=10;
Bobj.B1=20;
Aobj.display(Bobj);
Bobj.display(Aobj);
return 0;
}
put the functions that uses the forwarded class in another (.cpp) file where you can inlcude the whole class and hence can use the members
It should be something like this.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
#include <iostream>



class A;
class B;

class A
{
public:
    int A1;
    void display(B b);
};

class B
{
public:
    int B1;
    void display(A a);
};

void A::display(B b)
{
    std::cout << "B:" <<b.B1 << std::endl;
}
void B::display(A a)
{
    std::cout << "A:"<< a.A1 << std::endl;
}


int main()
{
    A a;
    B b;

    a.A1 = 10;
    b.B1 = 20;

    a.display(b);
    b.display(a);

    return 0;
}

Last edited on
Forward declarations are incomplete types. So how can you call the public methods of an object without completing the type?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
//Example 1:
class B;

class A
{
    public:
       int A1;
       void display( B objB ); //Okay you are just telling it what to expect
};


//Example 2:
class B;

class A
{
    public:
        int A1;
        void display( B objB ){ cout << objB.b1 << endl; } //not okay what is 
        //inside the class? All we know is  we are looking for type B
       //but there is no definition of it yet
};

Thanks a LOT!
Topic archived. No new replies allowed.