0

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;
}
2
  • 3
    There's no problem here. The program has undefined behaviour.
    – Kerrek SB
    Jun 14, 2016 at 11:16
  • You cannot just assume offsets like that to access a member variable. There are ways to determine the offsets but you cannot simply assume a value due to padding, vtables, etc. Also see here Jun 14, 2016 at 11:21

2 Answers 2

2

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

1

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.