7

I want to understand "this" pointer. I thought that "this" pointer refers to the value of the class object. However, in the below code, I could see different values of "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;
}

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 to understand this.

Thanks.

Coder
  • 845
  • 1
  • 10
  • 20
  • I think your actual question is when and why a pointer's value changes when its passed to a function that takes a pointer to a different class. – David Schwartz Feb 04 '16 at 18:17
  • I found your question very interesting, and I ve struggled myself very much in order to undestand that. I posted an extended answer, with some figures trying to explain object layout in the corresponding (duplicate) question. Feel free to check it, it may help you! – sestus Feb 04 '16 at 18:34

2 Answers2

6

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

Correct. this always points to the object on which a member function is invoked.

I could see different values of "this" pointer

Oh, but you're not printing this (in globalA and globalB). You're printing obj which doesn't 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 the other type. The conversion is allowed because interfaceB is a base of concrete. The converted pointer will no longer point to this object, but a base class sub object. A sub object (base class instance or a member) may but might not have the same address as the main object. Sub objects of an object cannot share an address, so at most one sub object may have the same address as the main object - except in the case of empty base optimization.

eerorika
  • 232,697
  • 12
  • 197
  • 326
0

this is a pointer which refer to the object that invoke the member function.

The type of this depends on the member function.

For example for a class X, if the member functions is

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

2) volatile, then this is volatile X*

otherwise it is X*

dlmeetei
  • 9,905
  • 3
  • 31
  • 38