Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why changes to a private variable is also done to a public one?

Tags:

excel

vba

I have a public variable Public AssetFamilyCollection As New Collection which is a collection of the classe AssetFamily I've created.

Within a sub, I create an AssetFamily instance with Dim familyChosen As AssetFamily. Then when I've identified the AssetFamily I want in the collection I do Set familyChosen = AssetFamilyCollection(i)

At some point, I make changes on familyChosen property and I noticed that those changes have also been done to AssetFamilyCollection(i)

I thought familyChosen was a private variable, a copy from AssetFamilyCollection(i) and only exists inside the sub. Apparently not.

Why the public and private variable are impacted by the changes and not the private one in the sub ?

Thanks !

like image 482
TmSmth Avatar asked Mar 17 '17 17:03

TmSmth


People also ask

What happens when you change the type of any variable from public to private?

A private variable can only be accessed by the class where it is defined. This is completely different from public variables which can be accessed by other classes as well.

What is the difference between public and private variables?

A public member is accessible from anywhere outside the class but within a program. You can set and get the value of public variables without any member. A private member variable or function cannot be accessed, or even viewed from outside the class. Only the class and friend functions can access private members.

Can private variables be accessed in public methods?

Answer 51c025e6282ae349350092d1 But after the object is created you can only access the private variable through the public methods of the constructor and no longer change it directly in any way.

Why do variables need to be private?

By making the variable a private data member, you can more easily ensure that the value is never negative. On the other hand, if the variable is public, another class could change it to a negative value which can cause other parts of the code to crash.


1 Answers

No it doesn't work like that.

The variable familyChosen is actually a reference to the same object as the array element is referring.

So you can modify that object either through that reference or through the array element.

like image 88
Bathsheba Avatar answered Nov 14 '22 21:11

Bathsheba