#include <stdio.h>
class B;
class A;
class A
{
int a;
friend int B::f();
};
class B
{
int b;
class A x;
public:
int f();
};
int B::f()
{
// ...
}
main()
{
class B b;
b.f();
}
ERRORS:
a.cpp:9: error: invalid use of incomplete type ‘struct B’
a.cpp:2: error: forward declaration of ‘struct B’
The issue cannot be solved by placing definition of B before A as B has an object of type A.
For this example making B a friend class would do, but in my real code I have more member functions in B (so I need alternative solution).
Finally, can somebody give me links that explain what the compiler does when it comes across a forward declaration, declaration, definition.
DefineB before A, and declare a pointer to A as member data of B:
class A; //forward declaration
class B
{
int b;
A *px; //one change here - make it pointer to A
public:
int f();
};
class A
{
int a;
friend int B::f();
};
Or, you could make the entire class B a friend of A, that way you don't have to make the member data pointer to A.
class B; //forward declaration
class A
{
int a;
friend class B;
};
class B
{
int b;
A x; //No change here
public:
int f();
};
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With