19172281
19172281

Reputation: 237

Providing pointer to private member from within class

I realise that providing a method which returns a pointer to a private method breaks encapsulation, and exposes the field to anyone who uses the class. However, suppose the following:

You have a class which calls the method of another class (which expects a pointer to some private field), and the address of the private member is passed as a parameter to this method.

As far as I can see, as long as the private member's address is only exposed in a way controlled by the developer of the class, this doesn't break encapsulation (i.e. the developer knows exactly how it's going to be used). Of course, the method called could (assuming you didn't write it) expose the private member, but do we need to look that far ahead? I've seen this done countless times, so I guess it's not the result of bad design practises?

Is it bad practise to write method which take pointers to private members of other classes and modify them? Should each class only "look out for themselves"?

Upvotes: 2

Views: 2065

Answers (2)

user4442671
user4442671

Reputation:

I realise that providing a method which returns a pointer to a private method breaks encapsulation, and exposes the field to anyone who uses the class.

This is not true to begin with.

A class that has a method that returns a pointer as part of its interface is absolutely fine, and the fact that it returns a member variable is an implementation detail that the outside world does not need to know.

Now, that being said, it is difficult to design a sane class interface that involves functions that return non-owning pointers, so it's something we tend to avoid.

Edit as far as the second part of the question goes:

Any class is supposed to sanely handle any possible permutation of usage of its public interface (including de-referencing any returned pointers). What or who uses the public interface is supposed to be entirely irrelevant, and you should assume that all users of the class will make use of the entire public API.

If you have parts of the class that you only want to make available to specific types or functions, then that's exactly what friend is for. But this has nothing to do with pointers to members, it applies to any and all parts of the class.

Upvotes: 0

Naveen
Naveen

Reputation: 56

It would be a bad design because most classes have getters and setters to read and write to the object. So if that function needs to read and write then it should ask for object reference, not for pointer to any private memeber.

And in most of cases when function needs a reference for variable, it asks for reference to a constant value.

Upvotes: 1

Related Questions