private member accessible from other instances of the same class

I just noticed something that I've never realised before. It turns out that 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;
    }
}

So different instances of the same class can access the private members of each other.

Up til now, I thought that the private members of an object could only be accessed by that object, not by other instances of the same class. It's a little suprising to find this out.

Is this the case in all common object oriented languages? It's not intuitive for me.

Answers


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.


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.


Need Your Help


About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.