returning reference to private vs public member

1.1k views Asked by At

I would like to know what could be reasons to provide a public access method returning a reference instead of making the member public. QPoint has methods int& rxand int& ry that let me directly manipulate the coordinates.

I guess the implentation looks similar to this:

public:
    int& rx(){return x;}
private:
    int x;

The only idea I had so far is the following: By keeping the member private and "only" providing a reference, the class can still change to use a different data type for its coordinates and while still "somehow" returning a reference to an int. However, this "somehow" would always need an int member. Once the reference leaked, the member pratically cannot change anymore. So this cannot be the reason.

In a related question the accepted answer suggests to rather make the member public instead of returning the reference.

Is there any benefit of returning a reference instead of making the member public (in the general case)? Or is this just Qt specific (QPoint specific?) design?

EDIT: QPoint in Qt4

1

There are 1 answers

9
Werner Erasmus On BEST ANSWER

In general, returning a member by reference breaks as much encapsulation as having a public member, and neither is encouraged.

I suppose when a class is sufficiently simple (plain old data-it is anticipated that neither interface, nor data will ever change), one could make all its members public. Returning a non const reference had the same effect. All encapsulation is broken.

With respect to your question, there is no benefit.

In addition to my answer, similar answers have been given here