Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Accessing a non static member of parent from a nested class's function

I tried snooping around for a similar question in the forum which could help me out without success.

I have a nested class in my C++ program. I am trying to access a variable of the parent class from a function in the nested class but am faced with the following error

ERROR: A non static member reference must be relative to a specific object

The variable I'm trying to access is protected and the nested class is public (and so is it's function)

Following is a code snippet depicting (or trying hard to) the scenario

Header File

class A
{
    protected:
        D x;

    public:

        int func1(int a);

        class B : protected C
        {
            int func2(int a);   
        }
}   

CPP File

int A::func1(int a)
{
    x = 5;
    B z;
    int b = z.func2(a);
}

int A::B::func2(int a)
{
    int c = x.getValue(a);      /* ERROR: A non static member reference 
                                   must be relative to a specific object */
}

From somewhere

A anObject;
anObject.func1(7);

The getValue() is a public function if that matters. Since I'm calling A's function through an object, and through that B's function, should that not be linked to that object and let me access that non static member?

like image 727
42cornflakes Avatar asked Jan 10 '23 07:01

42cornflakes


1 Answers

C++ internal classes are not like Java nested classes. There is no object inside another. They are just classes which namespace is another class, like Java static inner classes.

You have no access to the member x since it belongs to A, which is a completely unrelated class that has nothing (Inheritance, composite, etc) to do with B.

like image 166
Manu343726 Avatar answered Jan 18 '23 22:01

Manu343726