Question

Imagine that you have a situation like this:

class  className{
...
}

className func(){
    className cl;
    ...
    return cl;     
}

int main(){
    ...
    func();
}

What does the function func() return when you call it in the body of the program? A temporary copy of the object cl? I don't understand this, since in the body of the function func() you can get the address &cl, but you get an error if you try to call &(func()) inside the function main().

Was it helpful?

Solution

Inside the function you are dealing with a so-called lvalue shortly speaking with an object which address is known because the object is defined explicitly. The return value of the function is a temporary object (it is a so-called rvalue). Its address is not known. We do not know where the compiler defined this object. So we may not apply operator & to a temporary object.

Another similar example

struct A
{
   int x;
};

A f() { return A(); }

int main()
{
   f().x = 10;  // here the compiler will issue an error
}

This code shall not be compiled though for example MS VC++ 2010 will compile it due to either a bug or its language extension.:)

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top