Thank u so much Igor.
Was very much useful and informative.
objA = derived.Get(); // Didnt get any error at this line.
Why is that so? Compiles, builds and works fine.
Alamelu <Alamelu@discussions.microsoft.com> wrote:
But Bruno...
if i modify the same function as below.. it doesn't give any error..
const AClass& DerivedClass::Get()
{
return m_ObjA;
}
But my question is, even again here, it's equivalent to assigning a
non-const object to const reference. But why doesnt the complier
throw error here?
You are confusing two completely distinct situations: binding a
reference to an object, and assigning to an already-bound reference
(which is equivalent to assigning to an underlying object).
A reference must be bound to an object when it is created. Once bound,
it cannot be re-bound to a different object (aka reseated) - it becomes
an alias to an original object.
With this in mind, consider:
void DerivedClass::Get (const AClass &refA)
{
refA = m_objA;
}
const AClass objA;
derived.Get(objA);
At the point of invocation of Get(), a reference refA is bound to the
function argument objA, and becomes just another name for this object. A
statement in the body of the function is effectively equivalent to objA
= m_objA, which is illegal since objA is const.
const AClass& DerivedClass::Get()
{
return m_ObjA;
}
Here, the reference is a return value. A reference is created only when
the function returns, and is bound to the return value of the function.
No assignment takes place here: the function produces an (unnamed)
reference bound to m_ObjA. An assignment, if any, must take place
outside the function, at the call site. And of course, if the caller
does something like this
const AClass objA;
objA = derived.Get();
they'll get the same error as in the first case.
--
With best wishes,
Igor Tandetnik
With sufficient thrust, pigs fly just fine. However, this is not
necessarily a good idea. It is hard to be sure where they are going to
land, and it could be dangerous sitting under them as they fly
overhead. -- RFC 1925