5
#include<iostream>
using namespace std;

class A
{
    private:
        int value;
    public:
        A(int init):value(init){}
        void changevalue(A &a){a.value = 100;}//why a's value can be changed?
        void printvalue(){cout << value << endl;}
};

int main(int argc , char *argv[])
{
    A a(2);
    A b(3);

    a.changevalue(b);
    b.printvalue();

    return 0;
}

a is an instance of A class,with a private value named value,but why this private value can be changed? Is that the parameter list included in the scope of class?

std
  • 873
  • 2
  • 10
  • 17
  • You provided that interface in your class. Not providing the interface if you don't want one object to change another would solve your problem with it. The class itself is what has access to the private stuff, though, not the instance. – chris Sep 16 '12 at 14:41

2 Answers2

8

Because class access specifier apply on per class basis and not per object basis.

You can always modify the same type of object inside the class functions.Usual examples are copy constructor and copy assignment operator.

Alok Save
  • 202,538
  • 53
  • 430
  • 533
6

private doesn't mean "private to the object identity" but "private to the type (and friends)".

Note that accessibility and being able to write to the type are orthogonal concepts. You can always access a private value inside an object of your own type, but whether you can write to it or not depends on if the object is declared as const:

void f(A& a){ a.value = 4; } // OK: 'a' is not 'const'
void g(A const& a){ a.value = 4 } // error: 'a' is marked as ' const'
Xeo
  • 129,499
  • 52
  • 291
  • 397