Sabetay Toros
Sabetay Toros

Reputation: 79

C++ How to use a variable in a inner class that has been declared in Outer class

Is it possible to use a variable in an inner class declared in Outer class . I would like to achieve like the following. Is it possible. I am getting the following error.

prog.cc: In constructor 'Outer::Inner::Inner()': prog.cc:12:25: error: invalid use of non-static data member 'Outer::i' Inner( ) { i = 5; };

    #include <iostream>
using namespace std;
class Outer {
public:
    int i;
    class Inner; // forward declaration of Outer::Inner
    friend class Inner;
    class Inner {
        Inner() {
            i = 5;
        };
    };
};
int main() {
    return 0;
}

Upvotes: 0

Views: 2031

Answers (2)

P.W
P.W

Reputation: 26800

From the working draft of the standard available online:

9.7 Nested class declarations [class.nest]
A class can be declared within another class. A class declared within another is called a nested class. The name of a nested class is local to its enclosing class. The nested class is in the scope of its enclosing class.

Example:

int x; 
int y;
struct enclose {  
    int x; 
    static int s;
    struct inner { 
        void f(int i) { 
            int a = sizeof(x); // OK: operand of sizeof is an unevaluated operand 
            x = i; // error: assign to enclose::x 
            s = i; // OK: assign to enclose::s 
            ::x = i; // OK: assign to global x 
            y = i; // OK: assign to global y 
        } 
        void g(enclose* p, int i) { 
            p->x = i; // OK: assign to enclose::x 
        } 
    };     
}; 
inner* p = 0; // error: inner not in scope 

As you can see from the example provided in the document, the only way for a nested class to access a non-static member of the enclosing class is through a pointer to the enclosing class.

That is what happens in void g(enclose* p, int i)

Upvotes: 1

Botje
Botje

Reputation: 31080

Unlike Java, C++ "inner classes" have no connection to the outer class that created them. You will have to pass in a pointer or reference to the outer class.

Upvotes: 6

Related Questions