Nicolas Risso Nicolas Risso - 11 days ago 7
C++ Question

Compiling error when using struct within an inner class

I could not find any answer that helped me understand why the following code does not compile.
Im declaring a struct within the private part of a class (Foo), and trying to use it from within an inner class (Bar) like this.

class Foo {
public:
Foo();
class Bar;

class Bar {
public:
Bar();
Foo::Node createNode();
};

private:
struct Node{
Node(int d) : data(d) {};
int data;
};
};


And the compiler throws the following error:

.../Foo.h:9:14: error: no type named 'Node' in 'Foo'

Answer

You need to declare the inner class before referencing it:

class Foo {
    class Node;
public:

    // ...