marczoid
marczoid

Reputation: 1475

C++: Address-of dereference and dereference of an address-of

  1. Is *&x always equal to x? If not, when is it not?
  2. Is &*x always equal to x? If not, when is it not?

My guess is that (1) is always true, but (2) is not always true because x may not always be a pointer, so we cannot state *x.

Upvotes: 2

Views: 1014

Answers (2)

Sarthak Singh
Sarthak Singh

Reputation: 191

  1. Yes and No because *&x means that it is reference to a pointer meaning

    int v1 = 10; int *v2 = &v1; int *&v3 = v2; cout << *v3; *v2 = 11; cout << *v3;

will give out put 10 and 11.While declaring *&x does not mean get value of at address of v3. v3 in this context is the address of the pointer it is equated to. But if you use *&x outside declaration it will give you the value stored at address of v3.

  1. I belive second is illegal if & or * are not overloaded

Upvotes: 0

Jts
Jts

Reputation: 3527

In your first example you get the address of x (which gives you a pointer to x) and then you deference that pointer back to x. So yeah it should be, unless x is a class that has overloaded the operators * or &.

Your second example only works with pointers or classes that have overloaded the * operator.

If it's used with raw pointers, yeah it should be the same. You deference x, which returns a reference to the value stored in x, and then you get the address where that value is stored, which of course is x.

If it's used with a pointer to a class, and the class has overloaded the & operator, then it doesn't have to be.

class A
{
public:
    int v;
    //int operator*()   { return v; }
    int * operator&()   { return &v; }
};

A* w = new A();
int* ptr = &*w;    

Upvotes: 1

Related Questions