devxlogo

Avoiding Dependencies #2

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:

devxblackblue

About Our Editorial Process

At DevX, we’re dedicated to tech entrepreneurship. Our team closely follows industry shifts, new products, AI breakthroughs, technology trends, and funding announcements. Articles undergo thorough editing to ensure accuracy and clarity, reflecting DevX’s style and supporting entrepreneurs in the tech sphere.

See our full editorial policy.

About Our Journalist