Jump to content
  • Advertisement
Sign in to follow this  
Kiput

Classes

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

I have a general (noobish, I'm not quiet good in C++) question, how to do something like this in C++: class A { B cClassB; }; class B { A cClassA; }; From what I know this generates an error. Is there any way to do this?

Share this post


Link to post
Share on other sites
Advertisement


// Predeclare classes
class A;
class B;

class A
{
B *b;
}

class B
{
A *a;
}







You need to predeclare your classes before you use them, otherwise you'd have a non resolvable circular dependency. Have a look at This thread for a related problem you may encounter (classes in separate files).

Share this post


Link to post
Share on other sites
Usually if you have this situation it is a result of poor design and you need to re-examine on overall structure of your classes. But if you need to do it you can do it like:


// Basically says "This class *will* exist somewhere"
class B;

class A
{
B* classB;
};

class B
{
A* classA;
};



Note that they have to be pointers.

----------
Andrew

Share this post


Link to post
Share on other sites
Correction there; at least one must be a pointer. (But usually it makes more sense for them to both be pointers, at least IME.)

The problem with having actual objects in both classes is a logical one: What would 'sizeof' either class be? Each contains some data, plus *itself* (via the 'other' class containing the 'other other' class, which is the current one), which recurses infinitely. A pointer is a fixed-size thing which can be invalid or point back at a previously-defined object, as needed, so that avoids the problem.

In Java, you can certainly do what you posted - but that's because there are pointers being used behind the scenes :) Different object semantics.

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.

We are the game development community.

Whether you are an indie, hobbyist, AAA developer, or just trying to learn, GameDev.net is the place for you to learn, share, and connect with the games industry. Learn more About Us or sign up!

Sign me up!