private member accessible from other instances of the same class

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

In C++, Java and C# access control is implemented as a static, compile-time feature. This way it doesn't give any run time overhead. Only per-class control can be implemented that way.


For the exact same scenario there is 'Object specific Private' in Scala vs 'Class specific Private' which is not supported in Java also.

class Foo {

  private[this] def contents // [this] marks the property as private to the owner

  def doFoo(other: Foo) {
    if (other.contents) { // this line won't compile
      // ...
    }
  }

}

This came as a surprise that such feature is not supported in other modern languages private[this] vs private, I understand this may be not a security risk as such considering it's still tied to the Class and you can still access all the private variables with reflection either way for eg Does reflection breaks the idea of private methods, because private methods can be access outside of the class?.

If you look at from Python language perspective, they don't even have scope feature as broad as in C#, in the end it is all about code organization, and from language design perspective it's the learning curve a new comer has to go through


How would you make a copy constructor for a class that does not expose all of its internal state through public methods?

Consider something like this:

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

The Car's public interface doesn't expose its Engine, but you need it to make a copy.

Tags:

Oop