Home / Tips / C++ Tips / C++: When we are required to find offset of an element within a structure?

“Chishiki” is Japanese for “knowledge.” e-chishiki.com aims to bring software developers, information security professionals, IT executives and other IT pros a rich body of knowledge in the form of articles, interviews, tutorials and technical discussions. Our contributors are among the biggest names in the Indian IT industry and include noted authors, educators and practitioners.

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.

On Sale From April 2008

Let Us C
8th Ed.
C programming classic & best seller. 1 million+ copies sold!

Y. Kanetkar

On Sale From April 2008

Introduction to Object Oriented Programming & C++

Y. Kanetkar

On Sale From Fall 2008

Microsoft .NET Framework: Web Application Security

Vijay Mukhi

On Sale From Nolvember 2008

Quest C++ Courseware
12+ hours of instructional audio and animated slides.

Y. Kanetkar Asang Dani

On Sale From November 2008

A Programmer's Guide to Web Application Security

Vijay Mukhi

Latest Forum Posts