Recursive includes in C++

Started by
6 comments, last by NotAYakk 17 years, 11 months ago
Hello I'm trying to make a simulation, using OOP with C++ and SDL. The problem is making all the classes in scope with all others. For example, the elevator and the person classes should know about each other, so I include the person.h file in elevator.h, but then, when trying to do the opposite - include elevator.h in person.h - I'm getting lot's of errors. How can I do it right? thanks!
Advertisement
You can use forward declarations for this.

person.h
#ifndef _PERSON_H_#define _PERSON_H_// forward declare elevatorclass Elevator;class Person{public:  ...private:  // can only have a pointer to an Elevator object   // since size of Elevator is unknwon  Elevator *elevator;  ...};#endif


elevator.h
#ifndef _ELEVATOR_H_#define _ELEVATOR_H_// forward declare personclass Person;class Elevator{public:  ...private:  ...  // again only a pointer ... maybe you can use a refrence also? I forget ...  Person *person;};#endif


Then in your .cpp files you can include elevator.h in person.cpp and person.h in elevator.cpp.

Hope that helped.

[Edited by - AsOne on May 1, 2006 7:49:08 PM]
Arik: take a look at potential pitfalls #2: http://www.gamedev.net/reference/articles/article1798.asp
AsOne forgot to add the "#endif"s to the bottom of the files, but other than that his code is what you need to do. Also known as Include Guards.
^^^ Thanks for pointing that out, it's now fixed.
I believe their is a much more deeper problem then recursive includes. Why does the Person need to know about the elevator? This can potentially lead to some very coupled and unorthogonal design. For every actor you have are you going to require the player to know about that actor? Hopefully not.

A couple strategies to decouple the two objects.
* Event, messaging system
* Base Actor class that elevator can derive from.

- Dave
Thanks :)
That's what I needed.

Dave: not all the people have to "know" all the elevators, and not all the elevators have to know all the people.
They should know about each other because the elevator contains a list of persons, and a person should be able to call elevator methods.
I'm trying to keep the objects independant from each other as possible, but they should interact somehow.
I find this cleaner:

elevator.h:#pragma once#ifndef elevator_h_included_#define elevator_h_included_class elevator;#include "person.h"class elevator {  // etc};#else#pragma message("#pragma once failed on " __FILE__)#endifperson.h:#pragma once#ifndef person_h_included_#define person_h_included_class person;#include "elevator.h"class elevator {  // etc};#else#pragma message("#pragma once failed on " __FILE__)#endif


This topic is closed to new replies.

Advertisement