Forward Declaration of class in C++, incomplete type

You simply cannot use a forward declaration here. CReference needs the full declaration of Internal .

Commented May 31, 2013 at 12:36 You should use a pointer to Internal if you want to forward declare it. Commented May 31, 2013 at 12:36 possible duplicate of When to use forward declaration? Commented May 31, 2013 at 12:37

4 Answers 4

Forward declarations are useful when the compiler does not need the complete definition of the type. In other words, if you change your Internal data; to Internal* data or Internal& data , it will work.

Using Internal data; , the compiler needs to know the whole definition of Internal , to be able to create the structure of CReference class.

9,542 10 10 gold badges 68 68 silver badges 117 117 bronze badges answered May 31, 2013 at 12:36 Kiril Kirov Kiril Kirov 38k 23 23 gold badges 116 116 silver badges 193 193 bronze badges

Almost a perfect answer. All that's left is to mention that he can move the definition of Internal above CReference and it will work.

Commented May 31, 2013 at 12:39

@RickYorgason - of course, but I guess the OP knows that, looks obvious, as class Internal does not need to "know" about class CReference .

Commented May 31, 2013 at 12:40

Forward declaration only allows you to use pointers and references to it, until full declaration is available

answered May 31, 2013 at 12:36 24.8k 14 14 gold badges 64 64 silver badges 91 91 bronze badges

To use a type as a member of a class the compiler has to know how big it is, so that the size of the class can be correctly calculated. A forward declaration doesn't provide that information (C++ won't look ahead and try to find it, especially since the body might be declared in another translation unit), so you can't use it as a by-value member.

You can use a pointer or a reference instead, because pointers and references are the same size no matter what type they refer to. Then the compiler only needs to know the size of that type once you start manipulating it, and so you can get away without the full declaration until then.

answered May 31, 2013 at 12:39 Matthew Walton Matthew Walton 9,939 3 3 gold badges 28 28 silver badges 36 36 bronze badges

As mentioned above. Forward declaration has it's use to avoid header hell in header files when using only a plain pointer of a class in the header.

You usually want to keep includes in header files as few as possible. This can be achieved by forward declaring a class, but only if it is not a nested class and only if the pointer is used in header, as for this the pointer size is the required information, which is provided by the forward decl.