C++ Interlocking Classes

Member
Posts: 40
Joined: 2008.10
Post: #1
I have been trying to create a World class that can pass itself to an Object class so that the Object can react in a way to the World.
The only thing I can't figure out is how to include a class both ways.
I know it is possible.
Example:

class B
{
B();
~B();
update(G g);
};

class G
{
G();
~G();
B allTheBs[];
};


So you see I want both classes to be able to access each other.
Help please
?
Quote this message in a reply
Moderator
Posts: 1,140
Joined: 2005.07
Post: #2
You need to forward declare the class.
Code:
class G;
class B
{
   B();
   ~B();
   update(G g);
};

class G
{
   G();
   ~G();
   B allTheBs[];
};
Note that this will not work if you have G as a member variable. (a pointer to G is fine, though)

BTW, just a technical note, I hope that your real code doesn't have the parameter to update() declared as "G g". This will cause a copy of the G object you pass in to be made for the parameter. You should instead have "G &g", or if you don't need to modify G, "const G &g" to ensure that no copy will be made. Making the copy will also mess up your original object if you have pointers that are freed in the destructor, but don't define a copy constructor.
Quote this message in a reply
Post Reply 

Possibly Related Threads...
Thread: Author Replies: Views: Last Post
  Noob: Accessing Structures from Cocoa Classes MikeC 15 7,322 Oct 19, 2007 02:42 PM
Last Post: MikeC
  Trouble With Template Classes in C++ Nick 4 3,214 Nov 21, 2006 10:25 AM
Last Post: DoG
  Trouble with template classes ermitgilsukaru 2 2,668 Aug 11, 2006 02:00 PM
Last Post: ermitgilsukaru
  Noob: Copying Classes hangt5 3 3,515 Mar 9, 2005 12:52 PM
Last Post: codemattic
  First (pathetic) attempt at dual-weilding classes Coin 21 9,626 Feb 20, 2005 10:09 PM
Last Post: wadesworld