"Erik Bongers" <Bo**********@hotmail.com> wrote...
Nested classes only seem to be able to access static members of the
surrounding class :
class SurroundingClass
{
public:
class InnerClass
{
public:
void setSurroundingVariable()
{
SurroundingClass::variable = 4;
}
};
friend class InnerClass;
static int variable;
// int variable; --> ERROR : SurroundClass is not a base class
for type InnerClass
};
I would like to be able to access *instance* members of the
SurroundingClass, rather than only *static* members from within the
InnerClass.
I don't really understand why this is not working.
Perhaps I don't understand the concept of nested classes...
You probably don't. The big difference with, for example, Java's
"nested classes" is that in C++ an object of the surrounding class
_does_not_ by default contain an object of the nested class.
Anyone able to explain, and provide a solution for this problem.
Solution to what problem?
If you need a nested class to be a _data_ member of the surrounding
class, in addition to being a _type_ member, you need to say so:
class Surrounding {
class Nested {
double whatever;
public:
void somefunction();
};
Nested nested_data;
int some_other_data;
};
Now, 'nested_data' is _contained_ in an object of type Surrounding.
To further develop this, to give it access to it's "parent"s other
data members, you need to provide some mechanism, for example, the
'nested_data' member could be constructed to know its "parent":
class Surrounding {
class Nested {
Surrounding& papa;
double whatever;
public:
Nested(Surrounding&);
void somefunction();
};
Nested nested_data;
public:
Surrounding() : nested_data(*this) {}
};
Now, 'nested_data' contains a reference to the "parent" object,
which could be used to access other members of it.
I guess you just need to learn more C++ (and UNlearn some Java
while doing that).
Victor