tags:

views:

72

answers:

5

Hi

I've been reading some on forward declarations, including in this forum. They all say that it saves us from including the header file, However the following code generates an error:

#ifndef CLASSA_H_
#define CLASSA_H_

class B;

class A {

public:
    A();
    ~A();
    int getCount();
private:
    static int _count;
    int _num;
    B _b1;   //ERROR

};

compiler says: A.h:23: error: field ‘_b1’ has incomplete type

I noticed that if i make _b1 of type B* the problem is solved.

So is forward declaration good only for pointer types?
If i want A to hold B object i have to #inlcude "B.h" ?

thanks!

A: 

Yes, you would have to

#include "B.h"

if you want to include B in your class A.

Live
A: 

C++ compilers work in passes/phases. The forward declaration tells the compile that you are promising to define B at a later time.

Gabriel
This doesn't really answer the question.
David Thornley
Not completely true. The forward declaration is more like telling the compiler "trust me, this is a class", which is sufficient if you only want to have a pointer or reference to it, and are not planning to use it in that compilation unit.
Patrick
A: 

Yes, forward declarations work only if you use Pointers and References to the forward-declared type. If you use the object by value, you need to include the complete header file.

Matias Valdenegro
Well, forward declarations would work for using it as a type in function _declarations_, too: `B f(B);` You need the full definition of `B` to actually _define_ this function, though.
sbi
+5  A: 

The compiler has to know the exact definition of class B to determine at least what size to give to class A. If you use a pointer, it knows its size.

Note that circular dependancies are not possible. If you want

class A { B b; };
class B { A a; };

then A and B must have infinite size...

Alexandre C.
+1 i'm amazed i didn't know that
Gabriel
+2  A: 

You can use a forward-declared type to

  1. use pointers and references to it as data members
  2. use it as an argument (even taking per copy) or return type (even returning per copy) for function declarations.

You will need a full definition of a type in order to

  1. use it as class data member
  2. use it in function definitions.

If you remember that a forward-declaration actually is a misnomed declaration (there is no other way of declaring a class type, so any declaration of a class type is a forward declaration), and that, whenever you are opening the braces after class/struct/union plus identifier, you are defining a class, all you need to remember is that you:

  • need a full definition to use the type itself in definitions
  • get away with only a declaration to use the type itself in declarations
  • get away with only a declaration when you use only pointers and references and do not try to access members or nested types (anything with ., ->, and :: in front)
sbi