C++ Preprocessor: How to avoid problems with include files?
CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 1 of 1

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

  1. #1
    Join Date
    May 2000
    Location
    KY, USA
    Posts
    18,652

    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
    Code:
    // one.hpp
    #include <two.hpp>;
    
    class one
    {
      two two_instance_;
    };
    
    // two.hpp
    #include <one.hpp>;
    
    class two
    {
      one one_instance_;
    };
    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...


    Last edited by Andreas Masur; April 14th, 2006 at 06:27 AM.

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  


Windows Mobile Development Center


Click Here to Expand Forum to Full Width

This is a CodeGuru survey question.


Featured


HTML5 Development Center