Class in a Class !?!

Hello.

While reading a header file for an open source project I noticed something that puzzled me. Before the declaration of a class and after the includes the coder has placed the keyword class followed by the name of different class which is already defined in another file. I have created classes which had as members instances of different classes, but I only included the appropriate headers for the member objects. What is achieved by declaring the class within the class?
Last edited on
It's called a Forward Declaration.

It's used to reduce header file dependencies.

If class A is associated with class B, you could implement that as:
1
2
3
4
class A
{
    B b;
};
But that will require that the definition of B must be available when A is being defined.

Consider an alternative implementation:
1
2
3
4
5
6
class B;

class A
{
    B *b;
};
As the definition of A only needs to know that b is a pointer to class B, then it doesn't need to know anything else about B. So a forward declaration of B saying that it's a class is sufficient.

If A and B are in different header files, one need not include the other.

Further more, you can implement circular dependencies. For example, one header file can contain:
1
2
3
4
5
6
class B;

class A
{
    B *b;
};
while the other has:
1
2
3
4
5
6
class A;

class B
{
    A *a;
};
Thanks for the reply.

So the forward declaration in class A will suffice since A.h isn't referring to any method or member of class B? But then how are the dependencies reduced since presumably the implementation of A will need to include B.h? Is it in case some other class has an instance of A, I suppose?
I'd avoid doing that where possible, it's a bad habit to fall into.

Not that I can talk, since I use extern all over the place...
But then how are the dependencies reduced since presumably the implementation of A will need to include B.h?
Only the implementation of A needs B.h. If you had 10 other source files that used A and included A.h, they would not need to include B.h.
I see the point of it now. Thanks again.
Topic archived. No new replies allowed.