1

Although i have been using forward declaration for a considerable amount of time but never gave a thought to it seriously (my mistake)

Would be helpful if someone could give me pointers or any link regarding following queries :

  1. How do we determine if we require a forward declaration or include is required ?
  2. How does compiler actually works in such cases ? any overhead ?
  3. Suppose i have two interdependent classes A and B. Both of them uses objects of each other, do i need to forward declare in both the classes.
Dexter
  • 1,299
  • 3
  • 20
  • 38
  • Re marking it as a duplicate: it is, but the top answer in the original question isn't complete, and neglects the issue of instantiating templates. (To instantiate most of the templates in the standard library, you need a complete type. Otherwise, it's undefined behavior.) – James Kanze Jul 12 '13 at 08:12

2 Answers2

2

I'd say that:

  1. If you only need a reference or a pointer to a class in the header -> use forward declaration.
  2. The overhead with an include is that the compiler will see more dependencies for the current header, and will thus recompile your c++ body file perhaps unneccesarily.
  3. If possible yes.
jogojapan
  • 68,383
  • 11
  • 101
  • 131
Robert
  • 2,330
  • 29
  • 47
0

A forward declaration can always be used, when the compiler only needs to know that some object exists, but doesn't need it's size or other details iof the object.

For example in some .h file you have:

MyClass *foo(MyClass *p);

In example1.cpp:

// No include needed, forward declaration is ok.
MyClass *foo(MyClass *p)
{
    foo2(p);
    return p;
}

In example2.cpp:

// include needed, forward declaration is not ok.
MyClass *foo(MyClass *p)
{
    p->ClassFkt();
    return p;
}

In example3.cpp:

// include needed, forward declaration is not ok.
MyClass *foo(MyClass *p)
{
    MyClass *n = new MyClass();
    foo2(p, n);
    return n;
}

Here you have a prototype of a function which takes a pointer. A pointer is always of known size, so a forward declaration can be used here.

As long as you only use the pointer, for example to pass it on, to some other function, you don't need the include. If you try to access some members or do other operation which requires to know more details, you need to include the header file as well. In the above example1 you wouldn't need the full declaration and the forward declaration is sufficient. In the secaond example it is not, because the compiler doesn't know if your class has the function which is invoked. In the third example only pointers are used, but because of the new the size needs to be known, so a forward declaration is not enough.

In order to avoid extra header depencies, you can use the forward declaration in the .h file in the above example, and do the include only in the cpp file itself.

Devolus
  • 21,661
  • 13
  • 66
  • 113