C++: When we are required to find offset of an element within a structure?
When we are required to find offset of an element within a structure? Or, how do we call the function of an outer class from a function in the inner class? (The inner class is nested in the outer class).
#include <iostream.h>
class outer
{
int i ;
float f ;
public :
class inner
{
public :
infunc( )
{
outer *pout ;
pout = (outer*) this - ( size_t ) &( ( ( outer* ) 0 ) -> in ) ;
pout -> outfunc( ) ;
}
} ;
inner in ;
outfunc( )
{
cout << "in outer class's function" ;
}
} ;
void main( )
{
outer out ;
out.in.infunc( )
} In the above example we are calling outer::outfunc( ) from inner::infunc( ). To call outfunc( ) we need a pointer to the outer class. To get the pointer we have subtracted offset of the inner class's object (base address of outer class's object - address of inner class's object) from the address of the inner class's object.




Comments
Log in or create a user account to comment.