kubo
kubo

Reputation: 231

Can enclosing class access nested class?

I have the following code:

#include <iostream>
#include <string>

class enclose
{
    private:
        int x;
    public:
        enclose(void) { x = 10; };
        ~enclose(void) { };

        class nested1
        {
            public:
                void printnumber(enclose p);
        };
};

void    enclose::nested1::printnumber(enclose p)
{
    std::cout << "the number is " << p.x << std::endl;
}

int main()
{
    enclose example;

    example.printnumber();
}

I am aware that the last line example.printnumber(); is incorrect. However, I would like to know if there is any way that the enclosing class can access the nested class' functions. How can example access the printnumber() function?

Upvotes: 0

Views: 419

Answers (1)

Some programmer dude
Some programmer dude

Reputation: 409166

Can enclosing class access nested class?

Yes, if the enclosing class have an instance (an object) of the nested class.

A class is a class is a class... Nesting doesn't matter, you must always have an instance of the class to be able to call a (non-static) member function.

Upvotes: 1

Related Questions