Should we have friend....?
Ok hold it.... hold it....before you ask why I ask such a silly question...
I was talking about C++ lar!
Ok, this is probably my first technical-related posting...but I won't say anything, I will just ask the question and see what you people think.
My question is:
Does the "friend" access modifier in C++ enforce or break encapsulation?
Confession time: I used to say in class that you should avoid "friend" as much as you can (but I do use it sometime). however I have second thought about it now, not conclusive yet, but I would like to hear what you say. Hopefully if someone give a good comment that I agree, then I no need to write lo...:)
7 Comments:
Foo Yoh
Wow, now you have gone online into the internet. Share with us, what brings you here?
hmmm. recall back, i never use 'friend' in real life project before..
neither do I, and as far as Im concern I have already violated the encapsulation rule for so many times.
encapsulation : basic method for producing information hiding.
friend : allow access to another function or class.
As in the case of encapsulation vs friend.
- I think "No", because friend keep private things private, unless they simply use public declaration which already destroy the encapsulation itself.
Does this makes any sense ? hehehe :p
Thanks for the comments, will write something about this later, but much later as I am going to Beijing next week.
i agree that friend breaks encapsulation, but I would look at it from the reverse perspective. Its a tool to *intentionally* break encapsulation for the times when it really is needed. Its one of those things thats there incase you need it.
It's only a problem when you end up using it wrongly or, more commonly, prematurely before evaluating alternative approaches. Sometimes its a poor design, but at times it *can* be helpful to use friend functions.
personally, i've never used them in my own code libraries... but my encounters with Win32 API has occasionally necessitated 'friend' as a quick fix to a problem that would've otherwise taken a longer time to solve.
that's my 2 cents ;)
Thanks all for the comments, I really appreciate them. Do continue to give your views. I will write something about this later, but I am going to Beijing for conference tomorrow for a week, so got to wait till I come back.
I couldnt agree more with obsius, well said man !. It all depends on how the programmer wants to use it.
Post a Comment
<< Home