天天看點

Forward Declaration

What is wrong?

Forward Declaration

Fig. 1

In fig.1, the header file of class B contains the header file of Class D and E. We assume the implementation of Class A needs contents of class B and Class E. we decide that A.h includes B.h and A.cpp includes A.h (general case). Everything looks good. However if Class B is modified or upgraded so that it does not need class E anymore, Class A will not pass the compiler since it does not include Class E anymore.

What can we do?

We want to keep each class has its own encapsulation. However, we also want each class can decrease the number of including classes as much as possible in order to make it more independent. This is frustrated, but it is not the tradeoff. The integrity of the class is the highest priority.

In this case, the forward declaration is needed. We just declare the class in the header file and directly included in the cpp file. 

Forward Declaration

Fig. 2

In Fig.2, it is apparent that Class A needs contents of Class E. So if included Classes in Class B were changed, we should not be worry about if we have to modify the A.h as well. This is a three class chain example. You can imagine that if there is a 10 or more class chain which the top one only includes the next one under it. If the class before the last one changes the included classes and all those class do not have the forward declaration, it will be difficult to fix every errors after compiling.

The most potential cause of removing include E.h from the class B is that some members and functions in class E could be moved out and create another Class Z to contain them.  This code refactor will separate functions with better encapsulation.

Forward declaration can only be used without the conquered defined member. In the header file of A.h, we can only use the reference or pointer of the object E.h and allocate the memory size in A.cpp (new function).

繼續閱讀