Reference

Hello Forum,

I can do the following:
MyClass & objMyClass = MyFunction(); // MyClass & MyFunction();

Is there anyway to declare objMyClass and later use the "=" operater to set the operater? Or is there anyway to indicate at the beginning of the code that I will be using 'objMyClass', and then later on create&initialize it?

Thank you.
I don't understand the question. It is not possible to change the object that a reference is referring to. Using the = operator on a reference will do normal assignment on the object that the reference refers to.
Last edited on
MyClass & objMyClass = MyFunction();

This is wrong. The return value of MyFunction() is not an lvalue so you cannot declare an lvalue reference pointing to the return value of that function (references are used to 'refer' to other objects, but the return value of MyFunction() is not an object). Why are you using reference here at all?

(unless MyFunction() returns a reference to a global object)

And to your question, no you can't declare a reference without having it refer to an object. But can you tell us why you would want to do that?
Last edited on
Thank you for the responses.

I like to have all variables declared at the beginning of a function, just for overview. But I guess that is not possible with references, and also not the best thing performance wise for other sorts of variables.

MyFunction is a member function of a class, that returns a reference to an item, of an array-type variable inside that class.



If you really like to have all variables declared at the top of a function then you could use a pointer instead:
1
2
3
4
5
6
7
8
9
void f() {
int i;
char ch;
MyClass *obj;
...
// Note: obj does NOT own the object.
obj = &MyFunction();  // obj points to object returned by MyFunction
...
}

But yuck. That's an awkward thing to do in order to keep your desire to declare everything at the top. Just use a reference.

To understand why you can't assign a reference it helps to remember that a reference is a synonym for another object. So just as you can't change int i to refer to a different int in memory halfway through the program, you can't change int &i either. In both cases, the name is bound to memory when it's defined.

(unless MyFunction() returns a reference to a global object)
Not quite. It just needs to return a reference to a persistent object. A common example:
1
2
std::map<int,int> myMap;
int &i{myMap[2]};  // i refers to the mapped value. 


Ok, makes sense.

Thank you all.
Topic archived. No new replies allowed.