MWright
MWright

Reputation: 1711

C++ Using a Class Within a Class

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

Answers (3)

Alok Save
Alok Save

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:

  • Declare a member to be a pointer or a reference to the incomplete type.
  • Declare functions or methods which accepts/return incomplete types.
  • Define functions or methods which accepts/return pointers/references to the incomplete type (but without using its members)

But You cannot:

  • Use it as a base class.
  • Use it to declare a member.
  • Define functions or methods using this type.
  • Use its methods or fields, in fact trying to dereference a variable with incomplete type.

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

Björn Pollex
Björn Pollex

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

SmacL
SmacL

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

Related Questions