Since class definition is internal link, we must define a class before we use it. I can't figure out a situation to use class declaration, like class A;
. Is there?
-
1Possible duplicate of [When can I use a forward declaration?](http://stackoverflow.com/questions/553682/when-can-i-use-a-forward-declaration) – merlin2011 Mar 03 '16 at 05:58
3 Answers
That is a forward declaration, which is a method for dealing with circular dependencies in header files.
For example if two classes each hold a pointer to another, then you need to forward declare the class that is defined further down in the translation unit.

- 1
- 1

- 71,677
- 44
- 195
- 329
It is for forward declarations; imagine two classes having a pointer or mention to each other's instances:
class A;
class B;
class A {
class B*ptr;
int x;
/// etc
};
class B : A {
std::string s;
std::vector<A> v;
//// etc
};
It is also useful for readability; you might want to list all the classes first in some header.
And you could just forward declare a class and simply use its pointers without defining that class.
BTW, C99 has similar forward declarations for struct
, union
; and it is also useful to forward declare functions.

- 223,805
- 18
- 296
- 547
You are asking about need for forward declaration.
Imagine following hypothetical example:
class Man
{
Woman mySpouse;
};
class Woman
{
Man mySpouse;
};
we must definite a class before we use it.
Yes. So you can see for above example, this is impossible chicken-egg situation (aka circular dependency). This is why you need forward declaration and pointers, as shown below:
class Man; // Forward declaration
class Woman; // Forward declaration
class Man
{
Woman * pMySpouse;
};
class Woman
{
Man * pMySpouse;
};
Thanks to forward declaration, this should work OK.
See answers to this question : When can I use a forward declaration?
-
1That make sense only if pointers are involved (perhaps indirectly) otherwise (if e.g. `Woman` had an additional field) your class would have inifinite size – Basile Starynkevitch Mar 03 '16 at 06:04
-
@BasileStarynkevitch That is exactly my point. Anyway, just edited my answer for better understanding. – vcp Mar 03 '16 at 07:04