a quick question about a header file

I am now reading the following header file:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
#ifndef PPP_H
#define PPP_H

#include xxx

namespace yyy 
{
      class cBlockInfo;

      class cSuperMatrix 
      {
      ...
      };

      class cBlockInfo 
      {
      ...
      };

}  // end of namespace
#endif 


My question is: what is the use of the first declaration of cBlockInfo, i.e. "class cBlockInfo;" on Line 8? Is it superfluous? Can I simply remove it, since cBlockInfo has its real declaration from Line 15 thru 18?

Thank you!
Last edited on
It's probably necessary. It's called a "forward declaration" and allows cBlockInfo to be used as an incomplete type. It's likely that cSuperMatrix needs it to be forward declared for it to compile.

See section 4 for an idea of what forward declarations do:
http://www.cplusplus.com/forum/articles/10627/#msg49679
If SuperMatix doesn't contain a BlockInfo object there's no need for forward declaration there, if it did contain a BlockInfo object or pointer to reference to one (as shown below) then you would need to forward declare it so that it wasn't undefined when SuperMatrix was being compiled.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
namespace yyy 
{
     class cBlockInfo;

     class cSuperMatrix 
     {
         public:
             cSuperMatrix(void);
             ~cSuperMatrix(void);

         private:
             cBlockInfo* bi;
     };

     class cBlockInfo 
     {
        //definition of cBlockInfo
     };

}  // end of namespace 
Last edited on
Hi Disch and quirkyusername,

Thanks. But do you guys think simply changing the order of cBlockInfo and cSuperMatrix can always be a workaround?
1
2
3
4
5
6
7
8
9
10
11
12
13
namespace yyy 
{
      class cBlockInfo
      {
      ...
      };

       class cSuperMatrix 
      {
      ...
      };

}  // end of namespace 
Last edited on
That might work, yes.

But then you have the same problem the other way around if cBlockInfo needs cSuperMatrix to be defined.
Disch,

Let's simplify our notations a little bit. Can both A and B contain the other as part of themselves? Like this:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
namespace yyy 
{
      class A
      {
      ...
       private:
       B* b;
      };

       class B 
      {
      ...
       private:
       A* a;
      };

}  // end of namespace   


If this is the case, then we are trapped in a deadlock loop, right???
bump up~
No, not necessarily. An even simpler example:
1
2
3
4
5
6
template<typename T>
struct Element
{
T value;
Element<T> *next;
};


would be a component of a linked list. That's completely legal because next isn't created automatically, just the space for the pointer is allocated.
Last edited on
hanst99,

Thanks for your comments. Great point! You are right: next doesn't have to be defined right away, it can be assigned at a later time. Then no deadlock at all.
Last edited on
Topic archived. No new replies allowed.