Login | Register   
LinkedIn
Google+
Twitter
RSS Feed
Download our iPhone app
TODAY'S HEADLINES  |   ARTICLE ARCHIVE  |   FORUMS  |   TIP BANK
Browse DevX
Sign up for e-mail newsletters from DevX


Tip of the Day
Language: C++
Expertise: Intermediate
Nov 30, 2000

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 <snafu.hpp> 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 <snafu.hpp>

class fubar
{
public: // parameter type

    void method1(snafu   value_parameter);     // 1 
    void method2(snafu * pointer_parameter);   // 2
    void method3(snafu & reference_parameter); // 3

public: // return type

    snafu   value_return();     // 4
    snafu * pointer_return();   // 5
    snafu & reference_return(); // 6

private: // 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.hpp

class snafu;

class fubar
{
public: // parameter type

    void method1(snafu   value_parameter);     // 1 
    void method2(snafu * pointer_parameter);   // 2
    void method3(snafu & reference_parameter); // 3

public: // return type

    snafu   value_return();     // 4
    snafu * pointer_return();   // 5
    snafu & reference_return(); // 6

private: // 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)
Jon Jagger
 
Comment and Contribute

 

 

 

 

 


(Maximum characters: 1200). You have 1200 characters left.

 

 

Sitemap
Thanks for your registration, follow us on our social networks to keep up-to-date