Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ : Understanding "this" Pointer [duplicate]

Tags:

c++

pointers

this

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.

like image 296
ash Avatar asked Feb 04 '16 17:02

ash


1 Answers

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.

like image 129
eerorika Avatar answered Oct 13 '22 10:10

eerorika