Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c++

I have two classes, A and B. Class B has no meaning except to class A and requires private access to A's members, so I feel it should be a private nested class.

Class A is already complicated, so I would like to keep the definition of Class B outside of Class A, maybe 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 error: qualified name does not name a class before ‘{’ token.

I try 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 error: field ‘my_b’ has incomplete type ‘A::B’.

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

like image 792
QuestionC Avatar asked Jul 17 '15 18:07

QuestionC


People also ask

Can nested class access private members of parent?

Static nested classes do not have access to other members of the enclosing class. As a member of the OuterClass , a nested class can be declared private , public , protected , or package private. (Recall that outer classes can only be declared public or package private.)

Can you forward declare a nested class?

You cannot forward declare a nested structure outside the container. You can only forward declare it within the container.

Can nested classes access private members?

Member functions of a nested class follow regular access rules and have no special access privileges to members of their enclosing classes.

Can nested class inherit outer class?

A static nested class can inherit: an ordinary class. a static nested class that is declared in an outer class or its ancestors.


1 Answers

You can have a pointer to B as a member, or a smart pointer. The reason you cannot have a member variable of type B and have it defined outside of A is that if the compiler have not seen the definition of a class it does not know its size therefore cannot figure out layout for A.

Another approach to the whole thing is to use a pimpl idiom, I think it would be ideal here.

like image 167
Alexander Balabin Avatar answered Sep 20 '22 04:09

Alexander Balabin