470,864 Members | 2,023 Online
Bytes | Developer Community
New Post

Home Posts Topics Members FAQ

Post your question to a community of 470,864 developers. It's quick & easy.

two class definitions which uses each other

sdf
Hi.

Sorry for lame question, but I'm puzzled.
What if I have:

class A
{
public:
class B some_method ();
};

and

class B
{
public:
class A some_value
};

Class definitions are separated to different header files. And
compiler (VS2008 and mingw checked both) cannot compile class A before
class B compiled.

So what is correct way to handle such situation?
Jun 27 '08 #1
3 935
"sdf" <dr*****@gmail.comwrote in message
news:f4**********************************@m45g2000 hsb.googlegroups.com...
Hi.

Sorry for lame question, but I'm puzzled.
What if I have:

class A
{
public:
class B some_method ();
};

and

class B
{
public:
class A some_value
};

Class definitions are separated to different header files. And
compiler (VS2008 and mingw checked both) cannot compile class A before
class B compiled.

So what is correct way to handle such situation?
You can't really do that. One way is to have class A some_method return a
pointer to class B, then class A doesn't have to know what class B looks
like, just that it exists:

class B;

class A
{
public:
B* some_method();
};

class B
{
public
A some_value;
};

As long as it's returning a value from a method/function and not containing
the class. If class A contained class B which contained class A, the size
of either of the classes would be infiinite.
Jun 27 '08 #2
What you have here is called a cyclic dependency. Google it and you
will get tons of items.

A class must know its size at compile-time, thus it must know the size
of all its internals like its attributes.

You can also use the Pimpl Idiom (Opaque Pointer) technique to resolve
the problem.

David

Jun 27 '08 #3
On 2008-06-17 04:06, metarox wrote:
What you have here is called a cyclic dependency. Google it and you
will get tons of items.

A class must know its size at compile-time, thus it must know the size
of all its internals like its attributes.

You can also use the Pimpl Idiom (Opaque Pointer) technique to resolve
the problem.
You do not have to go that far, a simple pointer will do, since the size
of a pointer is known:

class B; // forward declaration

class A {
B* b;
};

class B {
A a;
};

--
Erik Wikström
Jun 27 '08 #4

This discussion thread is closed

Replies have been disabled for this discussion.

Similar topics

1 post views Thread by Stuart Hungerford | last post: by
reply views Thread by Carlos Ribeiro | last post: by
7 posts views Thread by Carlos Ribeiro | last post: by
10 posts views Thread by Brett | last post: by
9 posts views Thread by jerry.upstatenyguy | last post: by
2 posts views Thread by Jeff Johnson | last post: by
By using this site, you agree to our Privacy Policy and Terms of Use.