简体   繁体   中英

Accessing Private Members with Cin inside Class

I'm little confused.. My Code is Below

#include <iostream>
using namespace std;
class Test {
    private:
    int x, y;
  public:
    void get(){
        cin>>x;
        cin >>y;
        cout << x;
        cout << y;
    }
};

int main ()
{
  Test obj;
  obj.get();
  return 0;
}

In this code I'm accessing private members using cin..!! Is it fine? because I think user can send values or access private members directly after program run..!! I just want to ask is it safe or not..!! Thanks..!!

Read more about C++ member accessors.

Private members are only accessible within the class defining them. The get() function belongs to the Test class so it can access private members.

People have already answered, but I want to give a full answer:

In this code I'm accessing private members using cin..!! Is it fine?

In the code, you're getting values from cin and storing them in member variables. That's allowed, but not a normal way to write code. As others have stated, each Test object has access to its own internals, and as written, it will update those internals using data from cin . It's hard to imagine a useful language that could prevent you from doing this.

I think user can send values or access private members directly after program run..!!

No, the user could not. After the program exits, the memory is freed and all values simply cease to exist.

Even while the program is running, the user won't have access to the objects' internals. Yes, you ask the user for values, and then immediately tell the user the values they gave you, so there are no secrets; but the user doesn't get unrestricted access to x and y . After setting x to 5 , the user can't change it to 10 if the program never calls get() again. You can read the source code, and mark every place that the value is allowed to change; it will never change mysteriously without you calling get() . A true security hole would make it possible for the value to change without you knowing about it.

Within a class, private controls the accessibility of the name, not the actual data. So a class member function is permitted to pass a reference to a private member to any other function.

The line

cin >> x;

is actually a call to this function

std::istream& std::istream::operator>>(int&)

The code in get() (a member function) can see the name the variable x and can therefore form a reference to it, which it then passes on to operator>>() . As far as the code in operator>>() is concerned, it could be a reference to any int anywhere.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM