Forward declaring class

Hi,

Can you tell why forward declaring the class not work in below code? Compiler gives error 'B::a' uses undefined class 'A'

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
#include <iostream>

class A;

class B
{
public:
	int bInt;
	A a;

	int get_bInt()
	{
		return bInt;
	}
};

class A
{
public:
	int aInt;
	int get_aInt()
	{
		return aInt;
	}
};

void main()
{
	return;
}
Last edited on
The compiler need to see the full definition of A to figure out the memory layout of B, since directly contains an instance of A.
1
2
3
4
5
6
7
8
9
class A;

class B{
    A *a; //OK. sizeof(B) == sizeof(A *)
};

class C{
    A a; //Not OK. sizeof(C) == ???
};
I see. And if I replace A* with smart pointer to A in Class B, would behavior still be the same? i.e. No compiler error

Thanks.
Topic archived. No new replies allowed.