Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>Some of the potential problems with returning a pointer or reference to a private member:</p> <ul> <li>As you mention, encapsulation is breached. You have given access directly to the member, despite the fact it is private.</li> <li>If the <code>Text</code> class keeps some invariants over its <code>TextProperties</code> member, those may be invalidated by modifying the object from outside the class.</li> <li>The client code must be aware that the reference is only valid while the <code>Text</code> object that returned it is still alive.</li> </ul> <p>As your friend says, these would all be true if you just make the member public. However, maybe you want to do some extra work around simply returning the member (such as maintaining those invariants).</p> <p>Sometimes these are necessary issues to deal with if you really want the interface as you described. For an example of this in practice, take a look at <a href="http://en.cppreference.com/w/cpp/container/vector/operator_at" rel="nofollow"><code>std::vector::operator[]</code></a> - it returns a reference to the element. Note that the semantics of this function and yours are different, however - <code>std::vector</code> is a container, so <code>operator[]</code> is exposing the elements that are contained within (just like using <code>[]</code> on an array would). Instead, you are exposing some state of your <code>Text</code> object.</p> <p>If I had to pick between them, I would always recommend using the reference returning getter over returning a raw pointer (unless its possible for there to be no <code>TextProperties</code>, in which case you'd return <code>nullptr</code> (or use a <code>boost::optional</code>)).</p> <p>If acceptable, however, the safest and cleanest interface is to simply return the member by value and also have a setter that takes it by value. This should be your default approach, but you may not want to do this if copying the object around may be unnecessarily expensive.</p> <p>Just think about the tradeoffs and pick a design that best suits your class. Honestly, I can't see a reason why you wouldn't just get and set by value.</p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload