Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Address of &this instantiated class?

Tags:

c++

My goal is to write a function that returns the address of the instantiated class from which it is called.

My initial guess was

return &this

But this does not yield any good results.

Any and all suggestions are much appreciated! Thanks!

like image 689
icz Avatar asked Dec 21 '22 15:12

icz


2 Answers

Simply return this will return the address of an object from within that object.

like image 101
yan Avatar answered Jan 03 '23 03:01

yan


this is a pointer. You don't want the address of the this pointer, you want this itself.

Note that under virtual inheritance (virtual base classes, multiple inheritance), the this pointer may not be the same at all times (it would depend on where in the inheritance-graph it is pointing at the specific point in time).

Well defined conversions do exist (dynamic_cast) so no unsolvable problems there, just saying that you should not blindly believe that

MultiplyDerived* d = &someInstance;
Base* b = d;

bool test = ((void*) b) == ((void*) d);

test need not always be true (I think it is even compiler-dependent, i.e. implementation specific what happens when).

like image 30
sehe Avatar answered Jan 03 '23 01:01

sehe