Link to home
Start Free TrialLog in
Avatar of avi_india
avi_india

asked on

returning refrence to void poiter

I have following peace of C++ Code which compiles & runs perfectly fine on Sun & Microsoft but will not compile on HP 11


/********************************************/
#include <iostream.h>
int i;
class cls1{

public:
    void*& func1(int a, int b) {

         void *x;
     
         i=a+b;
         x=&i;

         return (void*) x;
    }
};

int main(){

    cls1 obj1;

    int * b;

    b = (int *)obj1.func1(5,6);

    cout<<*b<<endl;

    return 0;
}


/**********************************************/
Error Given on HPUX
Error (future) 438: "cls1.cpp", line 22 # The initializer for a non-constant reference must be an lvalue.
Try changing 'void *&' to 'void *const &' at ["cls1.cpp", line 16].                                
                     
   return (void*) x;
                            ^    

Error 582: "cls1.cpp", line 22 # Initialization of the result of "void *&cls1::func1(int,int)" requires
creating a temporary, yet the temporary's  lifetime ends with the return from the function.        
                   
   return (void*) x;  
                            ^

/*********************************************/
What could be the possible reason? Also what, if any, changes are required to do in this code so that
it runs equally good on all three platforms?
Avatar of chris_calabrese
chris_calabrese

The compiler doesn't realize that what you're returning (essentially  a reference to i) will still be in scope after the return.

Try changing the relevant code to simply:

void*& func1(int a, int b) {
        i=a+b;
        return (void *)i;
   }
ASKER CERTIFIED SOLUTION
Avatar of marecs
marecs

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial