0

I am writing a small c++ - program containing a similar structure to the following:

class A {
   B * someObjects;
};

typedef A* APointer;

struct B{
   APointer a;
   int n;
}

Trying to compile this gives a "identifier is undefined" error since struct B is not known inside class A. Otherwise declaring struct B before class A should still give a similar error, since then B does not know APointer, or APointer does not know A. Is there any possibility to make class A and struct B being good friends? Thanks in advance!

questioner
  • 93
  • 1
  • 6

2 Answers2

8

You need to forward declare B as the compiler has no idea what B is when it is used in A. B is considered an incomplete type in A and you are allowed to have a pointer or reference to B in A. You can change your code to:

struct B;

class A {
   B * someObjects;
};

typedef A* APointer;

struct B{
   APointer a;
   int n;
};
Community
  • 1
  • 1
NathanOliver
  • 150,499
  • 26
  • 240
  • 331
2

Have you ever heard the term Forward Declaration! Your compiler don't know about B yet. So give a declaration of B first.

struct B; // forward declaration 

class A {
   B * someObjects;
};
//... rest of the code
rakeb.mazharul
  • 5,423
  • 3
  • 18
  • 39