I’m having trouble understanding the value of this in the following example:
struct A {
int i;
void bar() {
cout << this << endl;
}
};
struct B : public A {
virtual void foo() = 0;
};
struct C : public B {
void foo() {
printf("hello world!\n");
}
};
int main (int argc, const char* argv[]) {
C* c = new C;
cout << c << endl;
c->bar();
return 0;
}
Both times I print the pointer to the console, I get different values. I would expect it to be the same, as they refer to the same instance both times?!
If I remove either the virtual function or the int i in A it goes away. Why?
But it refers to differnt things.
Here
thishas a typeA*. It points to the part of the object that isA.Here
cis aC*and points to the part of the object that isC.If the
Aobject lines up exactly with theCobject the pointers are the same. If they do not (like when C contains other members (hidden pointer to the vtable) and thus the ‘A’ part is offset from the start of the larger object) then the pointers are not necessarily the same.