Question

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 "

Was it helpful?

Solution

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.

OTHER TIPS

Here's the section about access levels in MSDN.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top