0

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?

kubo
  • 221
  • 1
  • 8

1 Answers1

1

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.

Some programmer dude
  • 400,186
  • 35
  • 402
  • 621
  • 3
    There was a change from C++11 onward. Nested classes can access protected and private members of the enclosing class. (https://stackoverflow.com/questions/5013717/are-inner-classes-in-c-automatically-friends ). But yes the nested class must have access to an instance of the enclosing first. (e.g. a reference to instance of enclosing class) – Pepijn Kramer Sep 10 '21 at 10:50
  • @PKramer Oh didn't know that. Answer updated. – Some programmer dude Sep 10 '21 at 10:55