The problem is that when you wrote:
void A_lookup(B b){ //this statement needs B to be a complete type
cout << b.b_i <<endl; //this also needs B to be a complete type
}
In the above member function definition, the parameter b
is of type B
. And for B b
to work, B
must be a complete type. Since you have only declared class B
and not defined it, you get the mentioned error. Moreover, the expression b.b_i
needs B
to be a complete type as well.
Solution
You can solve this by declaring the member function A_lookup
inside the class A
and then defining it later when B
is a complete type as shown below:
#include <iostream>
class B;
class A{
public:
int a_i=10;
//only a declaration here
void A_lookup(B b);
};
class B{
public:
int b_i=20;
void B_lookup(A a){
std::cout << a.a_i <<std::endl;
}
};
//this is a definition. At this point B is a complete type
void A::A_lookup(B b)
{
std::cout << b.b_i <<std::endl;
}
int main(void){
A a;
B b;
a.A_lookup(b);
}
Demo
Solution 2
Note that you can also make the parameters a
and b
to be a reference to const A
or reference to const B
respectively as shown below. Doing so has some advantages like now the parameter a
and b
need not be complete type. But still expression a.a_i
and b.b_i
will need A
and B
respectively to be complete type. Also, now the argument will not be copied since now they will be passed by reference instead of by value.
#include <iostream>
class B;
class A{
public:
int a_i=10;
void A_lookup(const B& b); //HERE ALSO void A_lookup(const B& b){ std::cout << b.b_i <<std::endl;} WILL NOT WORK
};
class B{
public:
int b_i=20;
void B_lookup(const A& a){
std::cout << a.a_i <<std::endl;
}
};
void A::A_lookup(const B& b)
{
std::cout << b.b_i <<std::endl;
}
int main(void){
A a;
B b;
a.A_lookup(b);
}
Demo
Also refer to Why should I not #include <bits/stdc++.h>?.