C++ Nested classes forward declaration error

I am trying to declare and use a class B inside of a class A and define B outside A. I know for a fact that this is possible because Bjarne Stroustrup uses this in his book "The C++ programming language" (page 293,for example the String and Srep classes).

So this is my minimal piece of code that causes problems

class A{
struct B; // forward declaration
B* c;
A() { c->i; }
};

struct A::B { 
/* 
 * we define struct B like this becuase it
 * was first declared in the namespace A
 */
int i;
};

int main() {
}

This code gives the following compilation errors in g++ :

tst.cpp: In constructor ‘A::A()’:
tst.cpp:5: error: invalid use of undefined type ‘struct A::B’
tst.cpp:3: error: forward declaration of ‘struct A::B’

I tried to look at the C++ Faq and the closeset I got was here and here but those don't apply to my situation. I also read this from here but it's not solving my problem.

Both gcc and MSVC 2005 give compiler errors on this

Answers


Define the constructor for A AFTER the definition of struct B.


The expression c->i dereferences the pointer to struct A::B so a full definition must be visible at this point in the program.

The simplest fix is to make the constructor of A non-inline and provide a body for it after the defintion of struct A::B.


Need Your Help

Could not get the ReportViewer dll's in GAC

reporting-services reportviewer report-viewer2010

I am trying to load ReportViewer dll's into the GAC. I downloaded the ReportViewer.exe from Microsoft's download website, Unblocked it and ran it as administrator. The installation of package was