I disagree with the idea that pointers are "dangerous weapons." They are simply a part of the language, and an integral part at that. There's nothing dangerous about pointers themselves -- the only thing that's dangerous is the ignorance of programmers who use them without knowing how to do so safely.
As to your question about overloading operator&
, my advice is: don't.
Let's broaden the question a bit here. You're not really asking about overloading operator&
. What you're really wondering is if it's appropriate to take heroic steps to prevent people from accessing the private
data members in your classes?
I say, no it's not. Just make private parts private
, and leave it at that. There are a couple of reasons.
First and maybe foremost, doing so increases code complexity. Every line of code you write is another potential source of bugs. The more "space age" or technical that code is, the more difficult the resulting bugs tend to be to identify and fix. It also makes your code more brittle, making it more likely that code you write in the future will break what you wrote today.
Next, it's futile to take these steps. I can almost guarantee you that no matter what steps you take to prevent me from modifying the private
data members of your class, I can find a way to defeat those measures. private
is like a lock on a door. It's not designed to make what's behind that door absolutely secure. It's really there to keep honest people honest, and dissuade the less determined dishonest ones. A determined, skilled programmer will defeat any lock you can devise.
Another reason is because, although it seems highly unlikely and extremely dubious, a programmer might try to access the private
members for legitimate reasons. You can't know all the ways in which your code might be used years from now. If a programmer can find a way to access the private
s in a way that is both legitimate and safe (eg, without invoking undefined behavior), you should not stand in their way. Obviously it would be best to simply modify your class rather than doing this.