0

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?

VLL
  • 9,634
  • 1
  • 29
  • 54
Jason
  • 169
  • 1
  • 11
  • 1
    Possible 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 Answers3

2

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.

Community
  • 1
  • 1
merlin2011
  • 71,677
  • 44
  • 195
  • 329
2

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.

Basile Starynkevitch
  • 223,805
  • 18
  • 296
  • 547
0

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?

Community
  • 1
  • 1
vcp
  • 962
  • 7
  • 15
  • 1
    That 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