Reputation: 354
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?
Upvotes: 8
Views: 959
Reputation: 71
A private property or method of a class means that it is not accessible directly from outside the class scope. For that public methods are defined inside a class through which we can access and manipulate the value of private members.
In the above example you are not directly accessing 'i'
from the object rather you are manipulating it through a public method.
Think it like this: You have a bank account and your money in the bank is private member. You cannot just directly go to bank and take your money by yourself. Cashier in the bank is like a public method that can access the private property i.e. your money, and you can manipulate your money though cashier.
Upvotes: 2
Reputation: 717
Isn't the private scope restricted to the same class even if the object is passed as a parameter?
Yes, this is what has happened x
is accessing the private member i
in the same class i.e in the class A.
Upvotes: 0
Reputation: 546153
private
in 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.
Upvotes: 13
Reputation: 6358
Variables x
and y
are two instances of the same class. They are different objects but they do belong to the same class. That's why is it possible to access the private member from the member function.
Upvotes: 5
Reputation: 5131
A class can access it's own private data members.
This also means if you have any functions that deal with two or more instances (this
and something passed as a parameter) you can access both object's private (and public) variables/methods
Upvotes: 0
Reputation: 25874
cpy(A x)
is a member of the class, it can access private
fields and methods.
The private
keyword limits intances from other classes (objects) to access the fields. Any code that belongs to a class can access its own private members (fields or methods).
Upvotes: 0