tags:

views:

27

answers:

2

I have been looking at a class that has a method that accepts a parameter that is of the same type of the class containing the method.

Public Class test
   private _avalue as integer
   Public Sub CopyFrom(ByVal from as test)
     _avalue = from._avalue
   End Sub
End Class

When used in code

a.CopyFrom(b)

It appears that instance "a" has visibility to the private members of the passed in instance "b" and the line

_avalue = from._avalue

runs without error copying the private field from one object instance to the other.

Does anyone know if this is by design. I was under the impression that a private field was only accessible by the instance of the object.

+2  A: 

You are writing something similar to to a copy constructor.
Since the copying method/function is being written inside of the same class, it will have access to private variables of any instance of its own class.

Binoj Antony
A sample in c# of copy ctor - http://en.csharp-online.net/Copy_Constructors
Binoj Antony
+2  A: 

The private scope is related to the type not the instance. So yes, this is by design.

The class test has knowledge about the private parts of itself, so it can use those parts also on other instances of the same type.

Fredrik Mörk
Thanks Fredrik, that makes sense.
Andrew