0

I understand that, for classes, private members can only be accessed by public members. But does that apply for each discrete instance of a class or can the public member of one instance directly access the private member of another instance.

For example, say there are two instances of class: instance1 and instance2. And say that the class has a private member x and public members getX() and setX(). If I want to set instance1.x equal to instance2.x which if the following would be correct:

instance1.setX(instance2.x)

Or

instance1.setX(instance2.getX())
Daniel Langr
  • 22,196
  • 3
  • 50
  • 93
  • 1
    Which is correct (I assume you mean "will compile") depends on the scope where it's supposed to appear. – StoryTeller - Unslander Monica Jan 26 '18 at 21:12
  • _"or can the public member of one instance directly access the private member of another instance"_? Sure. Otherwise, e.g., default copy constructor wouldn't be allowed to copy-construct private members. – Daniel Langr Jan 26 '18 at 21:12
  • First one is not allowed as `x` is private. You can't directly access `x` from object. Thus, you are left with second option only. – Nitin Jan 26 '18 at 21:20
  • Possible duplicate of [Why do objects of the same class have access to each other's private data?](https://stackoverflow.com/questions/6921185/why-do-objects-of-the-same-class-have-access-to-each-others-private-data) – Daniel Langr Jan 26 '18 at 21:23

3 Answers3

4

An instance of a class can see the private members of another instance of the same class.

An instance of a class cannot see the private members of another instance of a different class.

An instance of a class can see the public members of another instance of a different class.

When we say "can see", we mean that the members are in scope for the implementation of the class method.

class A
{
public:
    Foo() { x = 10; }                  // is legal
    Bar(A & another) {another.x = 12;} // is legal
private:
    int x;
};

int main()
{
    A a;
    A b;

    a.Bar(b);  // Is legal

    return 0;
}
Christopher Pisz
  • 3,757
  • 4
  • 29
  • 65
1

Inside code of that class member functions or its friends you can use

instance1.setX(instance2.x);
instance1.x = instance2.x;
this->x = instance2.x;
x = instance2.x;

Otherwise, you need to write

instance1.setX(instance2.getX());
Daniel Langr
  • 22,196
  • 3
  • 50
  • 93
0

Well, think about where you call instance1.setX(). Let's say you call it in some function foo():

void foo() {
    ...

    instance1.setX(instance2.x);

    ...
}

If foo() is not a member nor friend of your Instance class, then it can't access instance2.x; you'd have to use a getter here: instance2.getX().

Otherwise, you can use either method: instance2.x or instance2.getX().

frslm
  • 2,969
  • 3
  • 13
  • 26