-4

I'm studying about accessing private class members. I would like to understand better about this.

class Sharp 
{
public:
    Sharp();
    ~Sharp();
private:
    DWORD dwSharp;
public:
    void SetSharp( DWORD sharp ) { dwSharp = sharp; };
};

Sharp::Sharp()
{
    dwSharp = 5;
}
Sharp::~Sharp()
{
}

int _tmain(int argc, _TCHAR* argv[])
{
    DWORD a = 1;
    *(DWORD*)&a = 3;

    Sharp *pSharp = new Sharp;
    cout << *(DWORD*)&pSharp[0] << endl;

    cout << *(DWORD*)pSharp << endl;
    cout << (DWORD*&)pSharp[0] << endl;

    //pSharp = points to first object on class
    //&pSharp = address where pointer is stored
    //&pSharp[0] = same as pSharp
    //I Would like you to correct me on these statements, thanks!


    delete pSharp;
    system("PAUSE");
    return 0;
}

So my question is, what is pSharp,&pSharp and &pSharp[0], also please explain cout << (DWORD*&)pSharp[0] << endl; and why it outputs 0000005.

Thank you!

trincot
  • 317,000
  • 35
  • 244
  • 286
Vinícius
  • 15,498
  • 3
  • 29
  • 53
  • While not conventional, I suspect that it's nearly equivalent to `(DWORD *) &pSharp[0]`, which is the address of the 0-th element of `pSharp` as a pointer-to-`DWORD`. – Brian Cain Apr 28 '15 at 14:19
  • `cout << (DWORD*&)pSharp[0] << endl;` This is to get value which is store in array at index `0` and interpret it as pointer to `DWORD`. That's why the result is `5`. I guess you mean: `cout << (DWORD*)&pSharp[0] << endl;` – Piotr Siupa Apr 28 '15 at 14:30

2 Answers2

2

& is the "address-of" operator -- it can be applied to any lvalue and gives the address of (a pointer to) that lvalue. It is the opposite of the (unary) * operator.

So pSharp is a local variable (a pointer that points at heap memory), so &pSharp is the address of that local variable -- a pointer to a pointer.

&pSharp[0] is a little confusing, as postfix operators are higher precedence than prefix, so it is the same as &(pSharp[0]) -- the [0] dereferences the pointer, and then the & gets the address again, giving you bakc pSharp

Chris Dodd
  • 119,907
  • 13
  • 134
  • 226
2

what is pSharp

It's a pointer to a Sharp object instance.

what is &pSharp

It's the address of operator (it doesn't matter that this is a pointer).

what is &pSharp[0]

I don't know why it's written this way but it's just taking the address and the [0] just starts from the beginning of the memory addressed by the pointer.

why it outputs 0000005

Because the dwSharp class member is set to 5 in the constructor.

James Adkison
  • 9,412
  • 2
  • 29
  • 43