Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible for an object to access private field / function of another object of same class?

Tags:

f#

I know this is possible in C#, which produces simple and efficient code. --- Two objects of the same class can access each other's private parts.

class c1
{
    private int A;

    public void test(c1 c)
    {
        c.A = 5;
    }
}

But It seems impossible in F#, is it true?

type c1()
     let A = 0
     member test (c: c1) = c.A
like image 560
colinfang Avatar asked Sep 13 '12 11:09

colinfang


People also ask

Can objects of same class access private variables?

This is perfectly legal. Objects of the same type have access to one another's private variables. This is because access restrictions apply at the class or type level (all instances of a class) rather than at the object level (this particular instance of a class).

Can I access a private function of a class in the same class?

Private: The class members declared as private can be accessed only by the functions inside the class. They are not allowed to be accessed directly by any object or function outside the class. Only the member functions or the friend functions are allowed to access the private data members of a class.

Can we access private variable in another class?

We can access a private variable in a different class by putting that variable with in a Public method and calling that method from another class by creating object of that class.

Can an object access a private function?

An object user can use the public methods, but can't directly access private instance variables. You can make methods private too. Object users can't use private methods directly.


1 Answers

Interesting question. It seems to work with an explicit field but not with a let binding:

// Works
type c1 =
    val private A : int
    new(a) = { A = a }
    member m.test(c : c1) = c.A

let someC1 = new c1(1)
let someMoreC1 = new c1(42);
let theAnswer = someC1.test someMoreC1

// Doesn't work
type c2() =
    let mutable A = 42
    // Compiler error: The field, constructor or member 'A' is not defined
    member m.test(c : c2) = c.A 
like image 66
afrischke Avatar answered Nov 04 '22 16:11

afrischke