two class definitions which uses each other

S

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?
 
J

Jim Langston

sdf said:
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.
 
M

metarox

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
 
E

Erik Wikström

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;
};
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,755
Messages
2,569,536
Members
45,009
Latest member
GidgetGamb

Latest Threads

Top