Saturday, May 2, 2009

Why you should use forward declarations

Well I am sure you have always heard people telling you to use forward class declaration. I am not sure if you too have thought that what’s the point of it.

Well one best use case is in case of circular dependency. When you have a class A depended on class B and class B also references class A, you will be in a mess including header files in each other. So forward declaration would be a good way out of the mess, provided it meets certain conditions.

Another reason for using forward class declaration is that you will actually speed up the compilation time. Say you include class A as a pointer in class B and for that you have included header file of A in B. Then for any change in A, if it affects B in any manner or not, would lead to compilation of class B as well. This can be a serious pain point in case of large projects. If A has a forward declaration, then A would be compiled(obviously) and then at link time, compiler would make class B aware of A. 

But now the big question is, when can u not use forward declaration. Well answer to that question is very simple. Think like a compiler, in what situations would you be missing an actual declaration.

One of the reason can be when you are using the class as a base class. In that case u cannot determine the base class function  and the compiler cannot check for rules until it finds the declaration.

Another case is when you declare it as a member. In this case compiler has no clue about the size of memory to be allocated for this member. So forward declaration does not work here as well.

At times you want to define functions in the header file itself. In that case, if your function uses a forward declared class, it would throw a compile time error, because it has no clue about its properties.

Also its pretty clear that if you try and create an dynamically allocated object of class, forward declaration would not work if you try and call some function on that object. Again simply because the compiler would have no clue about that.

So friends its important that we use, forward declarations wherever possible. It does make life a lot more simpler, but then one size does not fit all Happy