How to define a nested class outside of its parent in C ++

I have two classes, A and B. Class B makes no sense other than class A and requires private access to the members of A, so I believe it should be a private nested class.

Class A is already complex, so I would like to keep the definition of class B outside of class A, perhaps in a separate header.

I tried this ...

class A;

class A::B
{
  int i;
};

class A
{
  class B;

  B my_b;
  int i;
};

int main (void)
{
  A my_a;
  return 0;
}

      

And get it error: qualified name does not name a class before ‘{’ token

.

I'm trying this ...

class A
{
  class B;

  B my_b;
  int i;
};

class A::B
{
  int i;
};

int main (void)
{
  A my_a;
  return 0;
}

      

And get it error: field ‘my_b’ has incomplete type ‘A::B’

.

This is similar to How to write actual code from a nested class outside of the main class , but complicated by the fact that class A has A :: B as a member.

+3


source to share


1 answer


You can have a pointer to B

as a member or a smart pointer. The reason why you cannot have a type member variable B

and define it outside A

is that if the compiler has not seen the definition of a class, it does not know its size, so it cannot determine the layout for A

.



Another approach to all of this is to use the pimpl idiom, I think that would be ideal here.

+5


source







All Articles