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?
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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With