1

Consider

1.

MyClass &myRef;

In This declaration is there memory allocated for myRef? What is the syntax of finding out the address of myRef?

2. Then if I do

myRef = someOtherRefToTheSameClass

Who is responsible for the implementation of this assignment?

Inisheer
  • 20,376
  • 9
  • 50
  • 82
OneGuyInDc
  • 1,557
  • 2
  • 19
  • 50
  • 2
    First off `MyClass &myRef;` will not compile. If you are asking if a reference takes up space then see: http://stackoverflow.com/questions/31521116/how-are-references-encoded-in-c – NathanOliver Nov 30 '15 at 19:03
  • MyClass &_foo; This DOES compile? – OneGuyInDc Nov 30 '15 at 19:15
  • 1
    @OneGuyInDc `MyClass &myRef;` would compile inside a class declaration but would need to be initialized in a constructor's initializer-list. Otherwise, a reference must always be initialized at the point of declaration. A reference cannot be re-assigned. – François Moisan Nov 30 '15 at 20:11

1 Answers1

1

References don't have an address. A reference is essentially a label for another variable, and if you take the address of a reference, you'll get the address of the thing it references.

Consider:

void function (bool b, int x, int y)
{
    int& ref = b ? x : y;

Here, &ref will evaluate to either the same thing as &x or the same thing as &y, depending on the value of b.

When you use a reference on the left side of an assignment, it acts the same as if you used the underlying variable. So if you have:

void function (SomeClass y)
{
    SomeClass &z (y);

Now, since z is a reference to y, y = foo(); and z = foo(); do the same thing.

David Schwartz
  • 179,497
  • 17
  • 214
  • 278
  • This does not answer either part of the question. – cdonner Nov 30 '15 at 19:11
  • @cdonner I guess we understand the question differently. I understand the question as basically, "I don't understand references and so these seem like the right questions to ask", so I gave the OP enough information about how references work so that those questions no longer make sense to ask. – David Schwartz Nov 30 '15 at 19:14
  • Fair enough. It wasn't clear what the OP wanted to achieve. – cdonner Dec 02 '15 at 00:00