how to access the outer structure member variable from inner struture?

D

dobest03

Hi.

Are there any way to access the integer member 'a' of outer structure
from
inner structure's member function func_inner()?
See below the structure...

Thanks.

struct outer {
int a;
struct inner {
int b;
void func_inner(void)
{
cout << "Inner func" << endl;
cout << "inner b: " << b << endl;
//cout << "outer a: " << outer::a << endl;
//cout << "outer a: " << a << endl;
}
} i;
void func_outer(void)
{
cout << "Outer func" << endl;
cout << "inner b: " << i.b << endl;
cout << "outer a: " << a << endl;
}
};
 
G

Gernot Frisch

dobest03 said:
Hi.

Are there any way to access the integer member 'a' of outer
structure
from
inner structure's member function func_inner()?
See below the structure...

Thanks.

struct outer {
int a;

// make inner a friend of outer
struct inner;
friend class inner;
struct inner {
// have a poitner to outer
outer& rOuter;
// no default c'tor: have to fill reference
inner(outer& out) {rOuter&out;}

int b;
void func_inner(void)
{
cout << "Inner func" << endl;
cout << "inner b: " << b << endl;
cout << "outer a: " << rOuter.a << endl;
}
} i;
void func_outer(void)
{
cout << "Outer func" << endl;
cout << "inner b: " << i.b << endl;
cout << "outer a: " << a << endl;
}

// constructor must initialize 'i'
outer(): i(this) {}


HTH,
-Gernot
 
M

Mark P

Gernot said:
// make inner a friend of outer
struct inner;
friend class inner;

There's really no need for this since the default access specifier for
members of a struct is public.
// have a poitner to outer
outer& rOuter;
// no default c'tor: have to fill reference
inner(outer& out) {rOuter&out;}

This is the right idea but a reference has to be seated in the ctor
initializer list, not in the ctor body.

inner (outer& out) : rOuter(out) {}

In any event, to state explicitly what your solution implies: an
instance of a nested class is not automatically associated with an
instance of the outer class-- indeed one can instantiate the inner class
without ever instantiating the outer class. (If memory serves, this is
in contrast to non-static Java inner classes which are always associated
with an instance of the outer class.)
// constructor must initialize 'i'
outer(): i(this) {}

Almost... should actually be:
outer() : i(*this) {}

-Mark
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,954
Messages
2,570,116
Members
46,704
Latest member
BernadineF

Latest Threads

Top