Initializing nested classes

I was wondering how to initialize objects from nested classes-

Example:
1
2
3
4
5
6
7
8
9
10
class Outerclass {
public:
    Outerclass();
    
    class Nestedclass {
    public:
        Nestedclass()
        int x;
    }
}


Then, how do I initialize the classes, so to get to the x variable, all I have to do is

outerClass.nestedClass.x=5;


Do I just do
1
2
Outerclass outerClass;
Nestedclass nestedClass;

?
Any help is appreciated.

Thanks.
Last edited on
Um, I don't see any reason for a nested class when you can just:

1
2
3
4
5
6
7
8
class A {
public:
    int foo;
};
class B {
public:
    A bar; // basically what it seems you're trying to do
};


1
2
B instance;
instance.bar.foo = 32;
Last edited on
Assuming the original post was just a "simplified" case of a more complex program,

you have to instantiate Nestedclass somewhere. As you've written it, all you've done is declared
Nestedclass to be a type whose scope is limited to Outerclass.

What you intend to do with Nestedclass is unclear. For example, is Outerclass supposed to contain an
instance of Nestedclass? Or is the user supposed to instantiate Nestedclass also?

Your proposed solution implies that the user is supposed to instantiate both, in which case the syntax
would be

1
2
Outerclass::Nestedclass nestedClass;
nestedClass.x = 5;

I want outerClass(object) to contain an instance of Nestedclass, so I access x by doing this:
outerClass.nestedClass.x=5
Is Zhuge's answer the only way to do this?
Because I want to define the Nestedclass(class) inside of the Outerclass definition.

Thanks.
1
2
3
4
5
6
7
8
9
class Outer
{
public:
    class Nested
    {
    public:
        int x;
    } nested;
};


Is that what you're trying to do? If you create an instance of Outer called outer, you'd be able to do outer.nested.x = 5.
Last edited on
I have the same doubt.....By making a single instance of outer class how can i use the innner class.....OR how can i make the object of inner class when i have the object of outer class....
Why would you want to do that? The point of a nested class is that it can only be instantiated inside the outer class.
Last edited on
Topic archived. No new replies allowed.