d3v-sci
d3v-sci

Reputation: 173

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;
}

Upvotes: 0

Views: 353

Answers (2)

TerraPass
TerraPass

Reputation: 1602

Your code sample is less about modification of private data members than it's about outright corruption of an object via a rogue pointer. I don't think there's a practical way in C++ to prevent crazy or evil programmers from doing just that.

private aims to protect sane clients from accidentally breaking the internal state of your object. Those who don't wish to play nice can simply do #define private public anyway.

I'm reminded of a quote by Herb Sutter, which is related to a different topic but I think it addresses your problem pretty well:

Remember, our concern is to protect against Murphy, not Machiavelli—against bugs and mistakes, not deliberate crimes—and such pathological abuses fall into the latter category.

Upvotes: 1

John Burger
John Burger

Reputation: 3672

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...

Upvotes: 2

Related Questions