Path: utzoo!attcan!uunet!cs.utexas.edu!news-server.csri.toronto.edu!utgpu!watserv1!watcgl!gbaciu From: gbaciu@watcgl.waterloo.edu (George Baciu [CGL]) Newsgroups: comp.lang.c++ Subject: Re: how do you define classes that refer to each other ??? Message-ID: <13867@watcgl.waterloo.edu> Date: 20 Mar 90 20:12:18 GMT References: <49689@wlbr.IMSD.CONTEL.COM> Organization: U of Waterloo, Ontario Lines: 77 In article <49689@wlbr.IMSD.CONTEL.COM>, mh@awds26.imsd.contel.com (Mike Hoegeman) writes: > > This is probably a stupid question, but here goes anyway. how do you > set up two classes that refer to each other ? Here's a simple example > to demonstrate my problem. ..... example changed for correct compilation below..... > > Now, the question is. How do I properly forward declare class 'stack' > to class 'thing' so that everybody is happy ? > > - mike hoegeman, mh@wlbr.imsd.contel.com This is a real problem in C++ and it is reminiscent of early implementations of Pascal. Now, most Pascal compilers have a "forward" keyword which allows circular declarations of procedural blocks. I wish C++ would provide the same sort of facility in the next releases. Now, in order to deal with circular declarartions in C++ I had to do the following: 0. declare the names of all the classes involved, as class x; class y; 1. data members of type class can only be references or pointers but NOT objects. 2. all the inline functions, implementing the methods containing the member classes involved, must follow the declarations of all the classes involved; this implies that you must have only the prototype declarations of the methods within the class itself. For your example, the following change should work: ------------------------------ cut here -------------------------------- class thing; class stack; class thing { int data[5]; public: void execute(stack&); // implemented after all classes }; class stack { thing stack_store[500]; int si; public: void push(thing *t); // this may be implemented here since stack() { si = 0; } // class thing is already declared. }; void stack::push(thing *t) { stack_store[si++] = *t; } void thing::execute(stack &s) { s.push(this); } main() { thing mything; stack mystack; mything.execute(mystack); } ------------------------------ cut here -------------------------------- Note, that the changed code compiles correctly with cfront 2.0. -- George Baciu ------------------------------------------------- | GBaciu@watcgl.Waterloo.edu GBaciu@watcgl.UWaterloo.CA | | * Computer Graphics Lab * | | University of Waterloo - Waterloo, Ontario, Canada - N2L 3B5 | ------------------------------------------------------------------