Jump to content
  • Advertisement
Sign in to follow this  
twoaterisn

Recursivity problem

This topic is 3616 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

Hello, I am trying to implement a molecule class, coded in C++. This class contains a list of atoms and a list of molecules. simple enough, right? However, performing some action on an atom will have implication on the bonds connected to it and performing actions on a bond will have implications for the atoms it connects. So I need to keep track of bonds in the atom class and i need to keep track of atoms in the bond class. like so: class atom{ private: bond * Itsfirstbond; //Of course,here the compiler complains } class bond{ private: atom * Itsfirstatom; } For functions this can be solved by separating implementation and declaration, but is there a way to do the same for variables? Or am i going about this thing completely wrong?

Share this post


Link to post
Share on other sites
Advertisement
You need to use a forward declaration. You simply say "class X;", which tells the compiler that a class called X exists. Until it is fully defined you can't make full use of it, but one of the things you can do is declare pointers to instances.

Your code would look like this:

// atom.h

class bond;

class atom
{
private:
bond * Itsfirstbond;
};

// bond.h
class atom;

class bond
{
private:
atom * Itsfirstatom;
}


You will need to include bond.h inside atom.cpp to make full use of the class.

Read this for more information and other tricks.

Share this post


Link to post
Share on other sites
What rip-off said. I had a similar problem last semester with a project that had multiple classes that were dependent on each other, and came to the same conclusion. Use forward declaration.

Share this post


Link to post
Share on other sites
Sign in to follow this  

  • Advertisement
×

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

GameDev.net is your game development community. Create an account for your GameDev Portfolio and participate in the largest developer community in the games industry.

Sign me up!