inheritance of class data

I'm looking for a way to use members of a class in a struct inside that class.
See example below. The real code is more complicated but I think this illustrates my problem wel enough. I get an error saying: "IntelliSense: a nonstatic member reference must be relative to a specific object"

Please help me.

1
2
3
4
5
6
7
8
9
10
11
12
  class A
{
public:
 struct B
 {
   void Function()
     {
       member += 123;
     }
 };
 int member;
};
You need an instance of the class A in order to access that variable. This is because it is possible to do something like:

1
2
typename A::B B_inst;
B_inst.Function();


Notice that in doing this, you have not instantiated the class A, so I believe that is why what you are trying to do is not compiling and you are getting the message
"a nonstatic member reference must be relative to a specific object"


But if you make the variable static, then this is possible:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
#include <iostream>
using namespace std;

class A
{
public:
	struct B
 	{
 		void Function()
 		{
 			A::member += 123;
 		}
 	
 	};
 	
 	static int member;
};

int A::member = 10; //Instantiate the static variable

int main() {
	typename A::B B_inst;
	cout << A::member << endl;
	B_inst.Function();
	cout << A::member << endl;
	return 0;
}
Last edited on
Topic archived. No new replies allowed.