c++oopprivatemembers

How to restrict objects private data member modification in C++?


please check the below code, i need a solution to restrict the modification of private data members of class A. please suggest.

class A{
private:
    int a;
    int b;

public:
    A(int i=0, int j=0):a(i),b(j){
        cout<<"A's constructor runs"<<endl;
    }
    void showVal(){
        cout<<"a: "<<a<<" b: "<<b<<endl;
    }
};

int main(){
    A ob1(10,20);
    ob1.showVal();

    int *ptr = (int*)&ob1;
    *(ptr+0)=1;
    *(ptr+1)=2;

    ob1.showVal();

    return 0;
}

Solution

  • There is nothing that you can do to prevent someone 'warping' pointers like that. You cannot prevent your private data from being deliberately or maliciously modified, only accidentally modified by users of your class.

    Unless of course you manage to get your data stored into read-only memory... You could get some memory from the OS, put your data into it, then get the OS to mark the memory as read-only - and only then 'publish' the pointer to your data. Of course, you can't modify your data either...