Sadique
Sadique

Reputation: 22821

Pointing to Static Class Member

class A
{
static int x;
};

How to get the Address of x using pointer-to-member ?

Upvotes: 2

Views: 2141

Answers (2)

Sarfaraz Nawaz
Sarfaraz Nawaz

Reputation: 361482

Since it's static, this should be this syntax:

int *px = &A::x;  //x is static member

For non-static member, this is the syntax:

 int A::*py = &A::y; //y is non-static member

Example:

struct A
{
  static int x;
  int y;
};

int A::x=100;

int main() {
        int *px = &A::x;
        int A::*py = &A::y;

        A a;
        a.y = 200;

        cout << *px << endl;   //used just like normal pointers
        cout << a.*py << endl; //note how the pointer-to-member is used!
        cout << a.y << endl;   //a.*py and a.y are equivalent!
        return 0;
}

Output:

100
200
200

Demo : http://ideone.com/0xSdW

Note the the differences between pointer to static members, and pointer to non-static members, and how they're used!

Upvotes: 7

Jesus Fernandez
Jesus Fernandez

Reputation: 1290

You can use &A::x. But remember to mark as public the variable and there will be only one X for all instances of the class.

Upvotes: 0

Related Questions