I have ever seen many cpp file that has "class xxxx;" in the first several lines. Is it only a declaration?seems not like that. what's it intended for??
-
I've never seen that before. Technically it's just a declaration of a class named `xxxx` I suppose. – cigien Apr 22 '20 at 02:58
-
1Probably forward declaration of a class, but to be sure you should add a small sample to the question. Where possible provide code rather than description of code. – user4581301 Apr 22 '20 at 03:09
-
https://stackoverflow.com/questions/4757565/what-are-forward-declarations-in-c – Jeffrey Apr 22 '20 at 03:10
-
1Does this answer your question? [What are forward declarations in C++?](https://stackoverflow.com/questions/4757565/what-are-forward-declarations-in-c) – rsjaffe Apr 22 '20 at 03:43
1 Answers
I have ever seen many cpp file that has "class xxxx;" in the first several lines. Is it only a declaration?
Yes. class xxxx;
is declaration of a class named xxxx
.
This particular declaration is not a definition of the class.
what's it intended for??
A class must be declared before it can be used in any way.
A declaration without definition in particular is needed when you have a set of classes whose definitions depend on each others declarations in a manner that forms a cycle. In such case there would be no way to order the definitions of those classes without violating the order of the dependencies.
Most simple example is two classes that depend on each other:
struct A {
B* x;
};
struct B {
A* x;
};
This is wrong, because A
refers to B
before B
has been declared. Let's try to change the order of the definitions to satisfy that requirement:
struct B {
A* x;
};
struct A {
B* x;
};
This is still wrong because now B
refers to A
before A
's declaration. We have exhausted all possible orders of definitions and must conclude that no order satisfies all the dependencies.
With non-defining declarations (often called a forward declaration), the solution is simple:
struct A;
struct B;
Now both classes have been declared, so either order shown above is allowed.
Forward declaration is also useful to avoid including a header that defines the class when that definition is not needed and declaration is sufficient. Unnecessarily including headers can have adverse effect in compilation time.
Another case where forward declaration is useful is when the definition of the class is intentionally hidden in which case it is called an opaque type. This is useful to limit API to a minimal set to hopefully avoid undesirable hidden dependencies on undocumented behaviour.

- 232,697
- 12
- 197
- 326