Reputation: 1711
I have a basic question that has bothered me for sometime.
When using a Class within a Class I can define the header of the Class I want to use in the header file. I have seen two ways of doing this and would like to know the difference between the two methods?
ex1
#include "ClassA.h"
class ClassB {
public:
ClassB();
~ClassB();
ClassA* a;
};
#endif
ex2 Here is the other way of doing it. The ClassA Header would be defined in ClassB source file.
class ClassA;
class ClassB {
public:
ClassB();
~ClassB();
ClassA* a;
};
#endif
What are the differences with these two methods?
Upvotes: 4
Views: 3914
Reputation: 206526
The comlpete layout of the classA
is known to the compiler when you include the class definition.
The second syntax is called Forward declaration and now classA
is an Incomplete type for the compiler.
For an Incomplete type,
You can:
But You cannot:
So Forward Declaring the class might work faster, because the complier does not have to include the entire code in that header file but it restricts how you can use the type, since it becomes an Incomplete type.
Upvotes: 9
Reputation: 76788
The latter is a forward declaration. This way you can declare a pointer or reference to a class, even though you have not yet fully declared it. This can be used to resolve cyclic dependencies. What if, in your first example, A
also wants to use a pointer to B
. This wouldn't work, because when A
is declared, B
is not known yet. To solve this, you can use a forward declaration to tell the compiler that there is a class B
, and you will tell it later what it looks like.
Upvotes: 0
Reputation: 22922
The second method only allows you to create pointers to ClassA, as it's size is unknown. It may however compile faster as the header for the full definition for ClassA is not included.
Upvotes: 1