Sign in to follow this  

Recursivity problem

This topic is 3288 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
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

This topic is 3288 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.

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this