Include loops

Started by
2 comments, last by Taile 22 years, 5 months ago
I am writing an upgradable encapsulation of everything. Don''t ask why. I guess I am a bit obsessive, or maybe I have a complex. Who knows? Well, anyway, I have one class called clsUniverse in clsUniverse.h and .cpp. Another class called clsObject is in clsObject.h and .cpp. clsObject can be stripped down to this: class clsObject { public: friend clsUniverse; //I hope this is legal - tell me private: bool exists; clsUniverse* the_universe; //the one that it "exists" in } clsUniverse can be stripped down to this: class clsUniverse { public: void Create (clsObject& an_object); // an_object.the_universe = this; } the clsObject.h file needs to include clsUniverse.h, but clsUniverse.h needs to include clsObject.h. That would mean they would keep including each other infinitely. How do I overcome this problem? I could do something like this: clsUniverse.h- #include "clsObject.h" clsObject.h- #ifndef _CLSUNIVERSE_H_ #include "clsUniverse.h" #endif Is there any other solution?
Advertisement
#pragma once

Although the method of defining a variable to mark inclusion of the header file is the most common (and compiler independent).

BTW a small aside if you are using the #define method, don''t put any underscore at the front of the symbol you''re using. Symbols which begin with underscores followed by a capital letter are reserved by both the C and C++ standards for compiler and SDK use. If you use names with underscores, don''t complain if you ever get a namespace conflict.

--
Simon O''''Connor
Creative Asylum Ltd
www.creative-asylum.com

Simon O'Connor | Technical Director (Newcastle) Lockwood Publishing | LinkedIn | Personal site

Forward declarations.

In clsObject.h (btw are you a VB programmer?):
class clsUniverse; // this is a forward declarationclass clsObject{  ...}; 

And then in clsUniverse.h:
class clsObject;class clsUniverse{  ...}; 

The downside to forward declarations is that you cannot reference any properties (data members) or operations (methods) of the class. The name is essnetially declareed as a placeholder.
So long as it is only a complex, you are doing fine. The day it becomes a quaternion, seek medical advice.

Each of your header file should be structured that way :

  #ifndef HEADER_FILE_H#define HEADER_FILE_H...#endif /* HEADER_FILE_H */  


Since your whole header file is bracketed by the #ifndef/#endif statements, any #include statement beyond the first will only add whitespaces to the file being processed.

Or, as Oluseyi said, if you only need to declare pointers/references/arguments, you can use a forward declaration.

The problem with #pragma is that they are compiler-specific.
"Debugging is twice as hard as writing the code in the first place. Therefore, if you write the code as cleverly as possible, you are, by definition, not smart enough to debug it." — Brian W. Kernighan

This topic is closed to new replies.

Advertisement