2009-09-21

Use Class Declaration in C++ Header File

A good C++ programmer always seeks to let his header files as slim as possible. The following header file is a bad example, in which an unnecessary header file is included.

#ifndef MYCLASS_H
#define MYCLASS_H

#include <SuperTime>

//bad, slow down the compilation
#include "Number.h"

//good. class declaration is sufficient for a pointer variable
//class Number;

class MyTime : public SuperTime
{

public:
MyTime(SuperTime *parent = 0);
int value() const;
void setValue(int value);

void valueChanged(int newValue);
private:
Number *number;
};

#endif // MYCLASS_H


This makes the compilation of big projects much slower, because the compiler usually spends most of its time parsing header files, not the actual source code. As suggested in the comments, use a class declaration instead including a header file. The final binary files are same as before, but this trick alone can often speed up compilations by a factor of two or more. Belows are the example of declaration of the template class and class with namespace:





template < class L > List;
namespace card {
class MainBrowser;
}

No comments:

Post a Comment