How do I define a pointer to a function which returns a char pointer?
Ans:
char * ( *p )( ) ;
or
typedef char * ( * ptrtofun )( ) ;
ptrtofun p ;
Here is a sample program which uses this definition.
main( )
{
typedef char * ( * ptrtofun ) ( ) ;
char * fun( ) ;
ptrtofun fptr ;
char *cptr ;
fptr = fun ;
cptr = (*fptr) ( ) ;
printf ( "\nReturned string is \"%s\"", cptr ) ;
}
char * fun( )
{
static char s[ ] = "Hello!" ;
printf ( "\n%s", s ) ;
return s ;
}
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)
Ans:
#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( ). Tocall 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 address of inner class's object.