can a class definition inside another class's definition

J

Jianli Shen

Hi,

I want to implement like this:

class A{

int length;

class B{
void operate_length_in_A(){
length++;
}

void use_length_in_A(){
if(length>8){
}
}

B *Bobj;

}

because B will use member in A, so I think I can not put B ahead of
definition of A.

How can I do?

Thanks
 
V

Victor Bazarov

Jianli Shen said:
I want to implement like this:

class A{

int length;

class B{
void operate_length_in_A(){
length++;
}

void use_length_in_A(){
if(length>8){
}
}

B *Bobj;

}

because B will use member in A, so I think I can not put B ahead of
definition of A.

How can I do?

Contrary to Java where a nested class is automatically instantiated as
a member of the outer class and also gets all members of the outer class
accessible and associated with the same instance of the outer class as
the nested instance, in C++ a nested class definition is nothing but
a definition of a type.

If you need to access non-static data members of the outer class (like
'length' in your example) from a function that is not a non-static member
of that outer class, you would need an instance to go along with it:

...
class B {
void operate_length_in_A(A& a) {
a.length++;
}
...

Where you put the definition of B inside A shouldn't matter.

V
 

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

Forum statistics

Threads
473,731
Messages
2,569,432
Members
44,832
Latest member
GlennSmall

Latest Threads

Top