Note that class x and y are two separate entities and you can not see their private data members from outside of their bodies.
It is known that from int main() I can not see the private member of class x or y.
My question in the following code in line 22:
Why class x can see the private members of class y ? (note here I am sending class y as reference not as a copy) isn't the referenced class y should be protected from strangers like class x ?
Note that the function getForeignNumber(const Player &r) inside class x is not a friend to class y!
#include<iostream>
class Account{
private:
int number{ } ;
public:
Account(int numberValue)
:number{numberValue}
{
std::cout<<"constructor is called"<<std::endl;
}
int getLocalNumber()
{
return this->number;
}
int getForeignNumber(const Account &r)
{
return r.number; // line 22
}
};
int main()
{
Account x{1};
Account y{2};
std::cout<<"get local number="<<x.getLocalNumber()<<std::endl;
std::cout<<"get foreign number x ="<<x.getForeignNumber(x)<<std::endl;
std::cout<<"get foreign number y="<<y.getForeignNumber(y)<<std::endl;
std::cout<<"Hello world"<<std::endl;
return 0;
}
CodePudding user response:
First of all, you are confusing instances of a class with the class. x
and y
are two instances of the same class Account
.
Your analogy isnt sound. Two instances of the same class aren't "strangers". They can access all the internals of each other. Thats how access works.
From cppreference:
All members of a class (bodies of member functions, initializers of member objects, and the entire nested class definitions) have access to all names the class can access. A local class within a member function has access to all names the member function can access.
In other words, access is per class not per instance. If x
would not be able to access y
s private members it would be impossible for example to write a copy constructor (without getter methods, which would be silly).
PS: By the way, "see" is the wrong word. There are certain circumstances where you can "see" that there is a private member from outside of the class, you just cannot access it. One such situation is when the name of a private method shadows that of a publicly inherited method https://godbolt.org/z/Kzf5KWv4W. Hence, even colloquially "see" is the wrong word for access.
CodePudding user response:
The function getForeignNumber()
can see private members of class Account
because getForeignNumber()
is a member of class Account
.
private
members are hidden from entities that are outside the class, not from other instances (objects) of the same class.