jeudi 28 juillet 2016

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

Aucun commentaire:

Enregistrer un commentaire