If this is your first visit, be sure to
check out the FAQ by clicking the
link above. You may have to register or Login
before you can post: click the register link above to proceed. To start viewing messages,
select the forum that you want to visit from the selection below.

C++ Preprocessor: How to avoid problems with include files?

Q: How to avoid problems with include files?

A: If you declare a class in your code the compiler normally needs to know some information about the used class like e.g. size. But if you just uses a pointer or a reference, the compiler doesn't need to know those information at that point since pointers or references are always the same size (4 bytes on a windows system). So you just need to tell the compiler that there will be a class - in this case called 'CSomeClass' - which will be used later by that declared pointer or reference. In this case you can use the so-called 'forward declaration'...

Code:

class foo
{
some_class some_class_instance_;
};

In this example you would need to provide the complete definition of 'some_class' since 'foo' will create one instance of it. Therefore the compiler needs to know the exact size of the class and how it looks like...

Code:

class some_class;
class foo
{
some_class* some_class_pointer_;
};

In this case you only have a pointer to 'some_class'. Since the size of a pointer is independent from the size of the object it is pointing to the compiler just needs to know that there is somewhere a class named 'some_class' is defined...

Most of the time forward declarations are used to prevent circular includes. Consider this

In this case you will end up with circular includes. While compiling the 'one.hpp' header file the header file 'two.hpp' will be included. While compiling 'two.hpp' header file the 'one.hpp' will be included. While compiling...

This will give problems even if you use inclusion guards like

Code:

#ifndef ONE_HPP
#define ONE_HPP
// Your class declaration
#endif

Therefore it is not necessarely a good idea to include all the needed header files within your header file. Using forward declarations will avoid those circular includes...for additional information about the whole subject take a look at the following FAQ...