Sign in to follow this  

Classes

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


// 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

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