5

I heard references in c++ can be intitalized only once but this is giving me 1 is my output and not returning any error!

 struct f { 
   f(int& g) : h(g) { 
     h = 1; 
   }

   ~f() { 
     h = 2; 
   } 

   int& h; 
 };

 int i() { 
   int j = 3; 
   f k(j); 
   return j;
 }
3
  • Didn't know that structs can be used in the same way as classes in C++. Good question.. Commented Aug 5, 2010 at 6:21
  • 1
    Nils: The only difference between a struct and a class in C++ is default accessibility. For classes the default is private, but for structs the default is public. For compatibility with C, methinks... Commented Aug 5, 2010 at 6:47
  • It's not an issue with reference but with scoping and object life-time. Commented Aug 5, 2010 at 8:30

3 Answers 3

9

The destructor of f is called after the return value j is captured.

You might want something like this, if you wanted j to be 2:

int i( )  
{  
    int j=3;  
    {
        f k(j);  
    }
    return j; 
}

See C++ destructor & function call order for a more detailed description of the order of destruction and the return statement.

Sign up to request clarification or add additional context in comments.

Comments

5

You are still initializing the reference only once; assignment and initialization are not the same. The initialization sets up h so that it references j (which you never change). Your assignment merely changes the value of j which is the same as h, but does not cause h to refer to a different variable.

Comments

0

I hope this code is only to display the issue, storing a reference to a variable defined outside of the class is very dangerous as your class doesn't have any control over (or knowlege of) when the referenced variable goes out of scope.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.