Avoiding Dependencies #2

Many C++ programmers will be familiar with the tidal wave of recompilations that occur when a seemingly unrelated header file is changed. C++ file dependencies need to be managed otherwise compilation times will grow unchecked. Large build times can cripple the process of creating software and eventually kill a project.

Suppose the class fubar uses the class snafu. Which uses require a #include in fubar.hpp and which ones don’t? Here’s a stylized code fragment that exhibits all possible uses (except inheritance which does require the #include).

 // fubar.hpp#include class fubar{public: // parameter type    void method1(snafu   value_parameter);     // 1     void method2(snafu * pointer_parameter);   // 2    void method3(snafu & reference_parameter); // 3public: // return type    snafu   value_return();     // 4    snafu * pointer_return();   // 5    snafu & reference_return(); // 6private: // object state      snafu   value;     // 7    snafu * pointer;   // 8    snafu & reference; // 9    private: // class state    static snafu   shared_value;     // 10    static snafu * shared_pointer;   // 11    static snafu & shared_reference; // 12};


The only one that requires a #include is number 7. A forward declaration will do for all the rest.

  // fubar.hppclass snafu;class fubar{public: // parameter type    void method1(snafu   value_parameter);     // 1     void method2(snafu * pointer_parameter);   // 2    void method3(snafu & reference_parameter); // 3public: // return type    snafu   value_return();     // 4    snafu * pointer_return();   // 5    snafu & reference_return(); // 6private: // object state      //snafu   value;   // 7    snafu * pointer;   // 8    snafu & reference; // 9    private: // class state    static snafu   shared_value;     // 10    static snafu * shared_pointer;   // 11    static snafu & shared_reference; // 12};


However, be aware that you can’t forward declare a class when:

  • The class is a nested class (there is no legal syntax to do it!)
  • The class lives in the standard library (prohibited by ISO C++)
  • The class is not a class! (e.g. a typedef’d template)
Share the Post:
Share on facebook
Share on twitter
Share on linkedin

Overview

Recent Articles: