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