Search code examples
c++classprivate-members

Way to set private variable of class having more than one member variable


As we can set the private variable of class like this

I was trying to set the private member variable int for below case.

#include <iostream>
#include <string>

using namespace std;

class Test
{
private:
    string s;
    int data;
public:
    Test() : s("New") , data(0) { }
    int getData() { return data; }
};

int main()
{
    Test t;
    int* ptr = (int*)&t;
    *(ptr+sizeof(string)) = 10;
    cout << t.getData();
    return 0;
}

But it is not able to print 10.

I know there are other way to set this using setter function, but was checking to set using method shown here

This is purely hack and not valid way though to learn.


Solution

  • I reckon this'll solve it:

    char* ptr = (char*)&t;
    *(int*)(ptr+sizeof(string)) = 10;
    

    sizeof will return the size in bytes. Pointer increments will go for the size of the object its pointing at. char is a byte in size.

    If you want to read up on it: C pointer arithmetic article

    Just to reiterate what I think you've said: you're just hacking around as a point of learning, and you know there's no way you should ever do this in real life... !!