Recursivity problem

Started by
1 comment, last by Chadwell 15 years, 3 months ago
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?
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.hclass bond;class atom{private:   bond * Itsfirstbond;};// bond.hclass 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.
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.

This topic is closed to new replies.

Advertisement