C ++ Using a class inside a class

I have a basic question that once bothered me.

When using a class in a class, I can determine the title of the class that I want to use in the header file. I saw two ways to do 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 another way to do this. The ClassA header will be defined in the source ClassB file.

 class ClassA; class ClassB { public: ClassB(); ~ClassB(); ClassA* a; }; #endif 

What are the differences between these two methods?

+4
source share
3 answers

The classA known to the compiler when a class definition is included.

The second syntax is called forward declaration , and now classA is an Incomplete type for the compiler.

For an incomplete type,
You can:

  • Declare an element as a pointer or reference to an incomplete type.
  • Declare functions or methods that accept / return incomplete types.
  • Define functions or methods that accept / return pointers / references to an incomplete type (but do not use its elements)

But you cannot:

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

So Forward A class declaration may be faster because the compiler does not have to include all the code in this header file, but it restricts the use of this type as it becomes incomplete.

+9
source

The second method allows you to create pointers only to ClassA, since the size is unknown. However, it can compile faster because the header for the full definition for ClassA is not included.

+1
source

The latter is a declaration. Thus, you can declare a pointer or a reference to a class, even if you have not fully declared it yet. This can be used to resolve circular dependencies. What if in your first example A also wants to use a pointer to B This will not work, because when A declared, B is not yet known. To solve this problem, you can use the forward declaration to tell the compiler that class B exists, and you will tell later what it looks like.

0
source

All Articles