cpp forward declaration

forward declaration and the friend class about the cpp.

c++ forward declaration and friend function

forward declaration

For the implementation, if two class has the hierarchy relationship, such as A will call the B and B may hold the pointer to the A, in this case, it is suitable to use the forward declaration when defining the class B.

Another solution for this part is to extract the public part used by A and B, then both A and B will refer to C, but the C does not need to hold the references to the A and B directly. Before using the forward declaration, it is important to consider if you could adjust the functions in classes and split another class to satisfy a clearer hierarchical relationship.

If we did not use the object-oriented programing, we may want to register separate functions to the program, in this case, we can use the forward declaration if the self-defined functions want to access other class instances defined in the system.

This answer provides a very good explanation and examples. I just list some points that need to pay attention to.

When we try to eliminate reference cyle and use the forward declaration, check the .h file and avoid the cycle of reference here. Then you could include the .h file (where the parent class is defined) of the parent class at the .cpp file (not the .h file) of the child class to make the forward declaration works. It is ok to forward declare the parent class at the .h file of the child class.

friend class

Sometimes I declare all elements in the class as the public items. In this case, I do not need to use a friend class. It is not a good thing to do. Sometimes I use more struct than the class to avoid the private member. I know it is not recommended. If you follow the rule of declaring the class and set the public/private members wisely, it might be necessary to declare a friend class sometimes to let dedicated class to access the private member of the current class. Here are some examples.

references

https://www.geeksforgeeks.org/what-are-forward-declarations-in-c/

https://www.geeksforgeeks.org/friend-class-function-cpp/

forward declaration

https://stackoverflow.com/questions/625799/resolve-build-errors-due-to-circular-dependency-amongst-classes

https://www.gamedev.net/forums/topic/562671-invalid-use-of-incomplete-type-and-forward-declaration/

https://stackoverflow.com/questions/4757565/what-are-forward-declarations-in-c/4757718#4757718

good material
https://stackoverflow.com/questions/4757565/what-are-forward-declarations-in-c/4757718#4757718

推荐文章