Nested Class Scope

Hello,

If I construct the nested class inside the outer class function, is there a way to make it available to the entire outer class?

Example:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
class Outer
{
   public:
         void makeClass();
         void someFunction();
         class Inner
         {
             public:
                doSomething();
         }
  private:
         int someInt;
};

void Outer::makeClass()
{
    Inner InnerClassName;
    InnerClassName.doSomething();
    someInt = 2;
}

void Outer::SomeFunction()
{
    InnerClassName.doSomething(); //InnerClassName undefined
}



Although I made an Inner class called InnerClassName, it's only usable in the function Outer::makeClass(). Can I make it so it's available in Outer::SomeFunction() too without passing it? I'm confused as to why the Inner class isn't avaliable to the entire Outer Class like SomeInt is once created. Thanks for any help.
You should declare an object of type Inner inside Outer then, just as you declared an int called someInt. Also, you forgot the closing semicolon on your Inner class definition.

The issue I think is that you don't see exactly what you're doing here. "someInt" is a member of type "int" and is thus available in all methods. "Inner" is a class type, but there is no instance to access until you create one like on line 17.
I see, I thought the uninitialized inner class would be saved like someInt.

Does that mean once makeClass returns from the call, the inner class called InnerClassName is destroyed?
Yes. I believe you wanted something like:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
class Outer
{
   public:
         void makeClass();
         void someFunction();
         class Inner
         {
             public:
                doSomething();
         }
  private:
         int someInt;
         Inner InnerClassName;
};

void Outer::makeClass()
{
    InnerClassName.doSomething();
    someInt = 2;
}

void Outer::SomeFunction()
{
    InnerClassName.doSomething();
}
Last edited on
Topic archived. No new replies allowed.