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

165 views Asked by At

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.

3

There are 3 answers

8
noelicus On BEST ANSWER

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

0
Barry On

Why it doesn't work

Really just never write code like this. There is a way to set private data and that is via public members on the class. Otherwise, it's private for a reason. This being C++, there are actually non-UB ways of doing this but I'm not going to link them here because don't.

Why it doesn't work, specifically

Hint: What does ptr + sizeof(string) actually mean, for ptr being an int*? What is ptr pointing to after this line?

0
default On

The pointer arithmetic should be done with byte pointers, not integer pointers.

#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;
   char* ptr = (char*)&t;
   *(int*)(ptr+sizeof(string)) = 10;
   cout << t.getData();
   return 0;
}