views:

1045

answers:

2

Here is a VB.NET code snippet

Public Class OOPDemo

    Private _strtString as String

    Public Function Func(obj as OOPDemo) as boolean
      obj._strString = "I can set value to private member using a object"

    End Function

End Class

I thought we cannot access the private members using the object, but perhaps CLR allows us to do that. So that means that access modifiers are based on the type and not on the instance of that type. I have also heard that c++ also allows that..

Any guesses what could be the reason for this?

Edit:

I think this line from the msdn link given by RoBorg explains this behaviour "Code in the type that declares a private element, including code within contained types, can access the element "

+3  A: 

Your question is quite confusing but I think I've understood it as: "Why can I access another instance (of my class)'s private variables?"

And you're right - in all OOP languages I've used you can access private variables from other instances, precisely because access permissions are based on where the code is, rather than to which object instance it 'belongs'.

It might be hard to implement copy constructors or equality operators otherwise.

Douglas Leeder
I just ran into this for the first time when auto-complete gave me the opportunity to access the other instance's private method. I take your point about copy constructors, but it still feels wrong to me from an encapsulation point of view.
ChrisA
+3  A: 

Here's the section about access levels in MSDN.

Lars