Question

class A
{
        class B
        {
                int x;
        }

public:
        void printX() { std::cout << ????; }
}

How can I access the x variable from the A class function? I can't make it static either...

I tried everything but it either tells me I need an object in order to access it or the compiler doesn't find the function.

Was it helpful?

Solution

it either tells me I need an object [...]

Think about that. Because that's exactly what the problem is here.

If you instantiate an A, you don't also get a B. A nested class isn't a member variable of the enclosing class. It's really just another way to change the namespace of a class.

So, you need an instance of B. Perhaps a member of A?

class A
{
        class B
        {
        public:
                int x;
        } mB;

public:
        void printX() { std::cout << mB.x; }
};

OTHER TIPS

You don't ever declare an instance of the class B inside A. You need to do something like this:

    class A
    {
            class B
            {
            public:
                    int x;
            };

            B b;

    public:
            void printX() { std::cout << b.x; }
    };

You don't. You do need an object in order to use the x variable. You could, however make it static. The problem with your example is x is not public. Placing B inside A does not make B part of A, it only changes B's scope.

From this example it kinda looks like you're after inheritance instead. This would give you the effect you're after ( access to all B's methods and variables without making an object. )

Class B
{
protected:
    int x;
}
Class A : B
{
    void printX() { std::cout << x; }
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top