Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ Using a Class Within a Class

Tags:

c++

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?

like image 421
MWright Avatar asked Dec 27 '22 12:12

MWright


2 Answers

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.

like image 174
Alok Save Avatar answered Jan 18 '23 19:01

Alok Save


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.

like image 28
SmacL Avatar answered Jan 18 '23 21:01

SmacL