In this post, we will see how to resolve Defining a nested class out of line in C++
Question:
Sorry if this has been asked before; I found similarly titled questions, but none of them focused on the same aspects I’m having trouble with.There’s a class A, and a class B that should only be accessible from A. I think nesting B inside A will achieve that, but I’m struggling with the logistics.
A has a B as a member. As such, not defining B prior to declaring A’s members causes incomplete type errors. I thought I’d get around this by declaring A, defining A::B, then defining A, but that just throws the same errors plus
incomplete type 'A' in nested name specifier
.Fallback options at this point include making A’s B a pointer (no real reason why not, but is this really something that can’t be done?) and leaving them as independent classes. But surely this can’t be that hard?
What do I need to declare to link these properly and in what order?
I am not particularly knowledgeable about the depths of C++ so please explain like I’m five and refrain from shaming me into the ground for not knowing everything.
Best Answer:
Sinceb
is a non-reference non static data member of class A
, it must be declared to have a complete type.One way to solve this would be to either make
b
a reference type(as shown below) or a pointer to a B
:Method 2
Other option is to define
B
inside A
with only its member declaration and then define those members outside as shown below:If you have better answer, please add a comment about this, thank you!
Source: Stackoverflow.com
Leave a Review