Skip to main content
GameDev.net gamedev.net
🔒 Locked

c++ object references

Started by newbie_99 Jan 6, 2001 at 4:33 PM 1 replies 350+ views
Original Post
newbie_99
newbie_99
I have a problem with a parent/child object setup. I can''t get it to compile b/c I seem to run into a "chicken or egg" type argument with the header files. Let''s say my classes are declared as below. I know i must be doing something stupid, but I can''t figure out what it is. The parent class needs to know what a child class is before it can compile, but the child needs to know what a parent is before it can compile. please help!!! ////////////////////////////////// // Parent declaration #include "child.hpp" class Parent { Parent(); ~Parent(); // data Child myChild; }; ///////////////////////////////// // Child declaration #include "parent.hpp" class Child { Child(Parent &); ~Child(); // data Parent &myParent };
jpbogart
jpbogart
This is very easy to fix -- simply add the following line after #include "child.hpp":
class Child;

and add the following line after #include "parent.hpp":
class Parent;

That''s it! This gives the compiler a generic class declaration to know that there are classes named Child and Parent that reside somewhere in the code.

Furthermore, you better #if/#endif out the files so you don''t get into trouble with recursive includes. Otherwise, just be careful not to include the files more than once.

For example, I would do the following -- at the very top of my header files, I put:

#if !defined(__FILENAME_H__)
#define __FILENAME_H__

//header file guts go here
//and the very last line is:
#endif

(Remember, only do this for header files, not source files)

Good luck!

jpbogart
Life, liberty, and the pursuit of better graphics...
newbie_99
newbie_99
Thank you! I thought I was missing something small. That works now!

Topic Locked

This topic has been locked by a moderator. New replies are not allowed.

Sign in to reply to this topic.