-2

Consider the following code:

std::vector &MyClass::getVector() const
{
    return (myVec);
}

void aFunc()
{
    std::vector *vec = &myClassInstance.getVector();
}

What adress does vec points to? Does it points to the very address of myVec in the myClassInstance object? (btw I know I should return a const ref, but it is an example).

Krapow
  • 611
  • 6
  • 26

3 Answers3

3

You are returning a reference to myVec in the method getVector. When you take the address of a reference, you get the address of the variable the reference refers to. So vec will contain the address of myVec.

keith
  • 5,122
  • 3
  • 21
  • 50
  • I wasn't sure about this behaviour. Thank you (as tobi303 suggested, i tried, and I confirm your answer ) – Krapow Apr 11 '16 at 13:09
2

A reference is an alias to another variable. When you return a reference tomyVec from getVector() then you can consider calling the function to be exactly like accessing myVec if it were publicly available.

&MyClass.myVec == &myClassInstance.getVector()

What adress does vec points to?

The address of myClassInstance.getVector() will be the same as the address of myVec.

Also note that since you are returning an lvalue reference you can even use it on the left hand side of an assignment like

myClassInstance.getVector() = some_other_vector;

And now myVec will be a copy of some_other_vector.

NathanOliver
  • 171,901
  • 28
  • 288
  • 402
0

Yes, it does point to the very vector myVec in your MyClass instance. See the following sample code:

#include <cstdio>
#include <vector>

class MyClass {
    std::vector<int> myVec;

public:
    MyClass() {}
    ~MyClass() {}

    std::vector<int>& getVector()
    {
        return myVec;
    }

    void printVector() const
    {
        for(std::vector<int>::const_iterator it = myVec.begin(); it != myVec.end(); ++it)
        {
            printf("%d ", *it);
        }
        printf("\n");
    }
};

int main(int, char**)
{
    MyClass item;

    std::vector<int>* vec = &(item.getVector());

    vec->push_back(1);
    item.printVector();

    return 0;
}

Running this program will output:

$ ./a.out 
1

So you can see that calling getVector() returns a reference to myVec from the MyClass instance, since we add a new item to the vector (vec->push_back(1)) via the vec pointer then print the MyClass instance's vector, and it shows that the item we added is there in myVec.

villapx
  • 1,743
  • 1
  • 15
  • 31