Sunday, July 26, 2009

'friend' access modifier in MS Visual Studio?

Does anyone have any idea why the 'friend' modifier in VB.net works the way it does? In VB.net (and other .net languages), the friend modifier allows the element to be accessed from anywhere in the assembly. But the way I learned it in Borland C++, a friend modifier didn't give universal assembly access, but allowed you to give selective access to other classes. For example:


--- code starts here ---


class a {


public:


void aFunc(void);


}


void a::aFunc(void) {


b *B = new b();


B-%26gt;bFunc();


}


class b {


friend void a::aFunc(void);


private:


void bFunc(void);


}


void main(void) {


a A;


b B;





// the following line is legal:


A.aFunc();


// the following line is illegal (it's private):


B.bFunc();


}


--- code ends here ---


'void a::aFunc(void)' is able to call 'void b::bFunc(void)', but main() is not allowed. 'a::aFunc' is a friend.





Why doesn't VB.net work this way? Is this one of the things that fell out of the obsolete AT%26amp;T C++ Standard?

'friend' access modifier in MS Visual Studio?
The "friend" access modifier in C++ is similar to the "internal" access modifier in VB.NET and C#. "friend" in VB.NET is similar to "protected internal" in C# and doesn't really have an analog in C++.





The main difference that you are seeing is that in C++ you explicitly state that another class has access to the friend class. In .NET either everyone in the assembly has access or not (with regard to the "internal" keyword anyway... obviously you can use public / private etc). In general .NET enforces encapsulation and OO principles more tightly than C++ does... which makes it better or worse depending on your point of view! :)
Reply:If what you are saying is correct, it would be weird behavior indeed. But I'm not an expert .Net programmer. so I don't know.





So, you are saying that the "B.bFunc();" would succeed in .Net, even if the bFunc was declared private???

floral bouquets

No comments:

Post a Comment