0
votes

ClassA has a member pointer to classB. I also added forward declaration of ClassB as a reference for the pointer b. I don't have #include "ClassB.h" in ClassA.h and ClassA.cpp. This code builds without error.

I'm confused how forward declaration alone is enough to successfully compile this code? If header is not required, what is the reference of the forwarded class?

I checked the other possible duplicates but it doesn't give clarity to my confusion since i'm not asking to fix the code here.

Can any one give clarity to my confusion.

ClassA.h

#ifndef CLASS_A
#define CLASS_A

#include <string>

class ClassB;

class ClassA
{
    ClassB *b;
};

#endif

ClassA.cpp

#include "ClassA.h

ClassB.h

#ifndef CLASS_B
#define CLASS_B

#include <vector>
#include  "ClassA.h"

class ClassB
{
    std::vector<ClassA> a;
};

#endif

ClassB.cpp

#include "ClassB.h"
1
When ClassA.h + ClassA.cpp compile into ClassA.o (or whatever), the ClassB* b member variable is of a known size. It only takes up a pointer, which is the same for all object pointers. - JohnFilleau
There are two things to unpack here: incomplete types resulting from forward declarations, and some magical thinking about headers that you have to disabuse yourself of. - Spencer
I realized that the include is not needed until i allocated memory for the member pointer. If i have a constructor in ClassA that allocates memory for member pointer ClassB, then, #include "ClassB.h" is required. now i get it. - winux

1 Answers

0
votes

I'm confused how forward declaration alone is enough to successfully compile this code?

class ClassB;

class ClassA
{
    ClassB *b;
};

This snippet does not need to know the definition of ClassB, so it works without including that definition. It is sufficient to know that the type exists in order to declare a pointer to the type. The declaration of the class achieves this.