icz
icz

Reputation: 547

Address of &this instantiated class?

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!

Upvotes: 5

Views: 7357

Answers (2)

sehe
sehe

Reputation: 393134

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).

Upvotes: 1

yan
yan

Reputation: 20982

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

Upvotes: 11

Related Questions