I am learning basic concepts of OOP in C++ and I came across a logical problem.
#include <iostream>
#include <conio.h>
using namespace std;
class A {
int i;
public:
void set(int x) {
i=x;
}
int get() {
return i;
}
void cpy(A x) {
i=x.i;
}
};
int main()
{
A x, y;
x.set(10);
y.set(20);
cout << x.get() << "\t" << y.get() << endl;
x.cpy(y);
cout << x.get() << "\t" << y.get() << endl;
getch();
}
I wanted to know in the above code why am I able to access x.i [Line 19] ,it being a private member in the different object.Isn’t the private scope restricted to the same class even if the object is passed as a parameter?
privatein C++ means private to the class, not private to the object. Both interpretations are possible, indeed some languages chose the other. But most languages are like C++ in this and allow objects of the same class to acces another instance’s private members.