Pointer values and inheritance

Jun 3, 2016 at 4:22pm
Could casting a pointer between two related classes change the value of the pointer?

More specifically, if I have a breakpoint in A::A(), assuming that I'm in the middle of constructing an instance of an unknown class B that may or may not inherit from other classes, is it safe to assume that the value of this that will be passed to B::B() will be the equal to that which was passed to A::A()?

Allowed assumption: using MSVC 10.0 targeting Win32.
Jun 3, 2016 at 5:27pm
Could casting a pointer between two related classes change the value of the pointer?

related by inheritance, I assume?

yes for implicit conversion, static_cast, dynamic_cast
no for const_cast, reinterpret_cast

will be passed to B::B() ... was passed to A::A()?

it's not clear from the explanation, but this order implies that A is one of the (possibly indirect) bases of B.

class B that may or may not inherit from other classes

If there are other non-empty base classes, then quite trivially, the this pointer in the constructor of B cannot equal the this pointer in each of its bases' constructors if it has more than one:

1
2
3
4
5
#include <iostream>
struct C { int c; };
struct A { int a; A() { std::cout << "A: " << this << '\n';} };
struct B : C, A { int b; B() { std::cout << "B: " << this << '\n';} };
int main() { B b; }

demo : http://coliru.stacked-crooked.com/a/2c02077e736303d3
Last edited on Jun 3, 2016 at 5:30pm
Jun 3, 2016 at 6:04pm
Thanks, that's what I thought.
Topic archived. No new replies allowed.