>>>On 02/09/14, Giuliano Bertoletti wrote:
>>> which is the difference of calling?
[snip]
>>> ==================
>>> MyClass c;
>>>
>>> SubObject &sub = c.GetSubObject();
>>> SubObject sub = c.GetSubObject();
On 09/02/2014, Marcel Müller wrote:
>> The second line creates a copy of SubObject.
[snip]
On 02/09/14, Giuliano Bertoletti wrote:> ok, thank you.
>
> Is it then safe to call:
>
> c.GetSubObject().SomeFunction()
>
> and expect a straight invocation of the original subobject (not a copy)?
That's right.
Note that such design is frowned upon by some people because it makes
the contract MyClass harder to grasp: Whoever gets access to the
instance of MyClass can also manipulate the sub-object at will. This way
it is not clear why the sub-object is a sub-object of MyClass and not
just an ordinary object that can be manipulated by both MyClass and
everybody else.
If you return a const reference (const SubObject&), however, it becomes
much clearer. The MyClass has full access to the sub-objects, but
clients of MyClass can no longer change MyClass's sub-object but only
retrieve information from it.
Regards,
Stuart