Shubham Batra
Shubham Batra

Reputation: 1278

Address of static member in a Class

How to get memory address of a private static member of a class in C++. In the below code I am accessing the private members of the class directly via their memory address.

#include <iostream>

class directM {
    int a;
    int b;
public:
    directM(int aa , int bb){
        a = aa;
        b = bb;
    }
    void show(){
        std::cout << a << b << std::endl;
    }
};

int main(){
    directM dm(10,20);
    dm.show();
    *(int*)( &dm ) = 15;
    *(int*)( ( (int*)(&dm) ) + 1 ) = 25;
    dm.show();
    return 0;
}

Now if I change one of the members and make it static i.e

static int b;

Now how would I be able to access this private member directly by its address.

Note:- I know this is a very unwise way to access the data and I am not using it to solve any problem. This is just a learning exercise to get to know the language better.

Upvotes: 2

Views: 2115

Answers (2)

Dai
Dai

Reputation: 155708

Ideally, you shouldn't and the language is designed to make it hard because it's marked as private.

If you change it to a public static member (so you can access it by name) then you can use the address-of operator thusly:

class directM { public: static int b; }

int* staticMember = &directM::b;

C++ makes no guarantees of the in-memory layout or organisation of static members, so this code is unsafe:

class directM {
public:
    static int first;
    static int second;
}

int* firstAddr = &directM::first;
int* secondAddr = firstAddr++;
assert( secondAddr == &directM::second );

Upvotes: 1

Mark Ransom
Mark Ransom

Reputation: 308530

Static member variables are not part of an object, their storage is completely independent. There's no way to know their location without accessing the variable name.

Upvotes: 7

Related Questions