Click to See Complete Forum and Search --> : Trouble with Forward Declaration


April 16th, 1999, 03:56 PM
I am having trouble with two classes that are referring to each other.

I am trying to create a simple event-based simulation driver. I have a root class "event" from which all types of events will be inherited. "event" will have a virtual "execute" method which will run the event, insert other events in the chain.

The container class, "eventlist" is simply a linked list with a pointer to the first, current, and last event. Each event has a pointer to the next one.

I want the "execute" method of "event" to return another instance of "eventlist", which will be a list of all events to insert into the main list. Then, a method of "eventlist" will take all of those events and put them in the proper place in the main list.

eventlist.h includes event.h. event.h does not include eventlist.h, obviously, so I put the forward declaration "class eventlist;" before the class definition of "event", so that when the compiler reaches the method "execute", and the return type is "eventlist", it will know what that is.

This all sounds good, but it is not working. I get the "class defn not found error". I tried making the return type a pointer to "eventlist", and it compiled, but when I tried to actually create an instance of "eventlist" inside "execute" I get a slightly different error "Cannot find default constructor" when there clearly is one in eventlist.h.

For some reason, the forward declaration is not working. Someone please HELP!

Thanks,

Reggie

Alvaro
April 16th, 1999, 04:22 PM
It looks like all you're missing is to include eventlist.h at the top of your event.cpp file.

Forward declarations inside header files work great when the compiler doesn't need to know anything about the class you're referring to. This is only true when you refer to a reference or pointer to the class (as a function parameter or return value); otherwise the compiler will need to know more information about the class and that's when the header file will need to be included.

Still, if your header files are properly guarded with macros like these:

#ifndef __HEADER_H__
#define __HEADER_H__

class ...

#endif // __HEADER_H__

you should be able to include them inside any CPP files you want. And in this case that's what you have to do to fix the problem.

Cheers!


Alvaro