Reputation: 889
I am a bit confused as to how the "this" pointer works with base and derived classes. Consider this code:
class A {
//some code
};
class B: public A {
//some code
};
Is it correct to assume that the "this" pointer invoked from class B will be pointing to the same address as a "this" pointer invoked from some code in the base class A?
What about multiple inheritance?
class A {
//some code
};
class B {
//some code
};
class C: public A, public B {
//some code
};
Is it correct to assume that the "this" pointer invoked from class C will be pointing to the same address as a "this" pointer invoked from some code in the base classes A or B?
Upvotes: 4
Views: 392
Reputation: 3018
Is it correct to assume that the "this" pointer invoked from class B will be pointing to the same address as a "this" pointer invoked from some code in the base class A?
No, you cannot assume this. However, although not required, many implementations will use the same address (tested with clang 11
and gcc 10
).
With multiple inheritance, in your example, clang 11
and gcc 10
use the same address for an instance of class C
and it's base A
. The base B
will have another address.
Another example is multiple inheritance with a common base instance:
struct A {};
struct B : virtual A {};
struct C : virtual A {};
struct D : B, C {};
Instantiating D
, we get with gcc 10
and clang 11
:
D: 0x7ffc164eefd0
B: 0x7ffc164eefd0 and A: 0x7ffc164eefd0 // address of A and B = address of D
C: 0x7ffc164eefd8 and A: 0x7ffc164eefd0 // different address for C
There are no rules specifying the relations between addresses of instances of a derived and a base class. This is implementation dependent.
Upvotes: 2