Access to a private member from other instances of the same class

I just noticed something that I had never understood before. It turns out this class is valid in C #:

class Foo { private string contents; public Foo(string str) { contents = str; } public void set(Foo other) { contents = other.contents; } } 

Thus, different instances of the same class can access each other's private members.

Until now, I thought that only this object can access private members of an object, and not other instances of the same class. It's a little surprising to find out.

Is this true in all ordinary object-oriented languages? This is not intuitive for me.

+8
oop
source share
2 answers

This is the same as in C ++ and Java: access control works on the basis of each class, and not on the basis of each object.

In C ++, Java and C # access control is implemented as a static compile-time function. Thus, it does not give any additional investment of time. This method can be implemented only for each class.

+8
source share

How would you create a copy constructor for a class that does not reveal all its internal state using public methods?

Consider something like the following:

 class Car { public: void accelerate(double desiredVelocity); double velocity() const; private: Engine myEngine; }; 

Car open interface does not reveal its Engine , but you need to do it.

+11
source share

All Articles