Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between &(*similarObject) and similarObject? Are they not same?

Can someone please explain this to me

dynamic_cast<SomeObject *>( &(*similarObject) );

What is the point of doing the address of a dereferenced pointer? Wouldn’t the pointer itself just be the address of it?

like image 292
poco Avatar asked Aug 05 '11 15:08

poco


3 Answers

It may be that the type of similarObject has overloaded operator* and so it returns something whose address you're passing to dynamic_cast.

&(*x) and x may not be always the same thing. For example, think of iterator:

std::map<int, int>::iterator it = v.begin();

Then it and &(*it) are two different thing:

  • The type of it is std::map<int, int>::iterator
  • The type of &(*it) is std::pair<int,int>*

They're not at all same. Similar thing may happen with your code-snippet as well.

like image 77
Nawaz Avatar answered Nov 03 '22 14:11

Nawaz


If similarObject is a smart pointer, this technique is sometimes used to get the reference of a raw pointer, when * has been overloaded.

like image 30
DanDan Avatar answered Nov 03 '22 14:11

DanDan


Nobody mentioned yet that similarObject is an lvalue, whereas &*similarObject is an rvalue.

like image 1
fredoverflow Avatar answered Nov 03 '22 14:11

fredoverflow