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.
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.)
You cannot forward declare a nested structure outside the container. You can only forward declare it within the container.
Member functions of a nested class follow regular access rules and have no special access privileges to members of their enclosing classes.
A static nested class can inherit: an ordinary class. a static nested class that is declared in an outer class or its ancestors.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With