Forward declaration is a technique that has at least 2 purposes:
For purpose #2, a TU (translation unit) that includes header file A but does not use the functions using the class defined in header file B and does not access that class, does not need to include header file B. That way if header file B ever change and forward declaration is used, this TU will not be recompiled. Taking systematically all the opportunities to reduce header file dependencies will not make a big difference on a project containing just a few TUs but it can save hours of compilation on big projects. Also, from experience, it is much easier to plan ahead and think about this aspect as the project grows than trying to remove the dependencies once they become a major problem for maintenance!
The reason why forward declarations work is because the compiler does not need to know the size of a class to generate code that handles pointer or reference to that type. A pointer or a reference always have the same size no matter the type.
Now that I have convinced you of the benefits of using forward declarations in header files, once you start using them, you might stumble on minor difficulties. How to forward declare a class inside a namespace? I have checked into the C++ bible 'The C++ Programming Language' from Bjarne Stroustrup and it remains quiet on the subject.
Fortunately, the answer is simple. Since namespace are open, all you have to do is:
namespace A { // Forward declaration class B; };
For nested classes, you can do it too but at the condition that it is done inside the outer class full declaration.
class B { // Forward declaration class C; };
is ok but
class B; class B::C;
is not. If this is something that you need, you either have to give up the forward declaration of B or move out class C out of B.
No Comments/Pingbacks for this post yet...
Comments are closed for this post.
I want you to find in this blog informations about C++ programming that I had a hard time to find in the first place on the web.
Sun | Mon | Tue | Wed | Thu | Fri | Sat |
---|---|---|---|---|---|---|
<< < | > >> | |||||
1 | 2 | 3 | 4 | 5 | ||
6 | 7 | 8 | 9 | 10 | 11 | 12 |
13 | 14 | 15 | 16 | 17 | 18 | 19 |
20 | 21 | 22 | 23 | 24 | 25 | 26 |
27 | 28 | 29 | 30 | 31 |