#include<vector>
using namespace std;
class Foo
{
  private:
    vector<int> m_vec;
  public:
    vector<int> getFoo()
    {
      return m_vec; // returns a copy of m_vec
    }
    vector<int>& getFooRef()
    {
      return m_vec; // returns a reference of m_vec
    }
};
int main()
{
  Foo foo;
  vector<int> x = foo.getFoo(); // init x with a copy of m_vec
  vector<int>& y = foo.getFooRef(); // y is a reference to foo.m_vec - no new copy is created
  vector<int> z = foo.getFooRef(); // what happens here?? Is the copy constructor invoked?
  vector<int>& a = foo.getFoo(); // what happens here?? Is `a` a reference to a copy of m_vec?
  return 0;
}
            Asked
            
        
        
            Active
            
        
            Viewed 90 times
        
    -3
            
            
         
    
    
        arunmoezhi
        
- 3,082
- 6
- 35
- 54
- 
                    1Possible duplicate of [What are the differences between a pointer variable and a reference variable in C++?](http://stackoverflow.com/questions/57483/what-are-the-differences-between-a-pointer-variable-and-a-reference-variable-in) – tkausl Jun 21 '16 at 00:50
- 
                    As `z` is not a reference itself, it will be initialized with a copy of `m_vec`. Reference to `m_vec` will be returned from the method, but assigning it to `z` will execute the [copy assignment operator](http://en.cppreference.com/w/cpp/language/copy_assignment). – Jezor Jun 21 '16 at 00:55
- 
                    thanks. that answers my question – arunmoezhi Jun 21 '16 at 00:58
1 Answers
3
            
            
        When you do this
vector<int> z = foo.getFooRef();
the compiler uses the reference on the right of the = operator to perform initialization of variable z to the left of the = operator.
The nature of the actual operation of initialization is determined by the left side, i.e. z. Since z is not a reference, operator = copies the content of the vector obtained by reference into z.
 
    
    
        Sergey Kalinichenko
        
- 714,442
- 84
- 1,110
- 1,523