C ++: Understanding the "this" Pointer

I want to understand the "this" pointer. I thought that the "this" pointer refers to the value of the class object. However, in the code below, I could see different values ​​for the "this" pointer:

#include <stdio.h> class InterfaceA{ public: virtual void funa() = 0; }; class InterfaceB{ public: virtual void funb() = 0; }; void globala(InterfaceA* obj){ printf("globalA: pointer: %p\n\r",obj); } void globalb(InterfaceB* obj){ printf("globalB: pointer: %p\n\r",obj); } class concrete : public InterfaceA, public InterfaceB{ public: void funa(){ printf("funa: pointer: %p\n\r",this); globala(this); globalb(this); } void funb(){ printf("funb: pointer: %p\n\r",this); globala(this); globalb(this); } }; int main(int argc, char *argv[]) { concrete ac; ac.funa(); ac.funb(); return 0; } 

The output of this program gives:

 funa: pointer: 0x7ffff67261a0 globalA: pointer: 0x7ffff67261a0 globalB: pointer: 0x7ffff67261a8 funb: pointer: 0x7ffff67261a0 globalA: pointer: 0x7ffff67261a0 globalB: pointer: 0x7ffff67261a8 

Any help for understanding this.

Thanks.

+6
source share
2 answers

I thought that the "this" pointer refers to the value of the class object.

Right. this always points to the object that the member function is called on.

I could see different values ​​for the "this" pointer

Oh, but you do not print this (in globalA and globalB ). You are typing obj , which does not even have the same type as this .

this is of type concrete* . When you pass it to a function that takes an argument of type InterfaceB* , the pointer is implicitly converted to another type. Conversion is allowed because interfaceB is a concrete base. The converted pointer will no longer point to the this object, but to an additional object of the base class. A subject (base class instance or member) may not have the same address as the main object. Object entities cannot share an address, therefore no more than one subobject can have the same address as the main object, with the exception of empty base optimization .

+5
source

this is a pointer that refers to an object that calls a member function.

The type of this depends on the member function.

For example, for class X , if member functions

1) const, then this is of type const X*

2) volatile, then this volatile X*

otherwise it is X*

0
source

All Articles