Re: How to assign a non-const object to const reference
if i modify the same function as below.. it doesn't give any error..
const AClass& DerivedClass::Get()
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
It's not the same. When you do
const AClass& DerivedClass::Get() const
the returned reference is const, so the caller cannot use it to modify
m_ObjA. This good, because it prevents the caller with messing with the
inside of (BTW, why did you make m_ObjA public -- this allows anybody
to modify it, defeating the purpose of the Get() method).
In your original method, you were assigning to refA, which was declared
const. You can only use const reference for input parameters. For output
parameters you should use non-const:
void DerivedClass::Get (AClass &refA) const
refA = m_objA;
If you use it like
then objA is now a copy of m_objA, so again it cannot be used to modify
m_objA, though the objA itself may be modified.
Your second method is really better, because it is more flexible. It can
be used like so
const AClass& objA = d.Get();
which requires no copy at all. Or it can be used like so
AClass objA = d.Get();
which does require a copy.
Note that both methods should be declared const, because they do not
modify the object.