If I have the following classes:
class A
{
public:
A(int val) : m_valA(val) {}
private:
int m_valA;
};
class B : public A
{
public:
B(int val) : A(0), m_valB(val) {}
private:
int m_valB;
};
B* pb = new B;
if I have a function which takes a A*, eg:
void func(A* pVal) {}
and pb is passed to this function, then in terms of low level memory layout, what is the difference between pval (in the function) and the pb pointer?
Doesn’t a pointer point to the beginning of the object? In which case how will the two pointers be different?
If you pass a pointer to a
Bobject tofunc(A* pVal), then inside thefunc()implementation thepValpointer will point to theAsub-object part of theBobject. It’s unspecified whether they will be at the same location (though for a simple inheritance situation as in your example, it almost certainly will be).If the
Asub-object is actually at a different offset (which might need to be the case if multiple inheritance is involved, for example), then the compiler will make the appropriate adjustment automatically when it compiles the call. The compiler can do this because at the call site it knows it’s dealing with aB*and needs to convert it to anA*to pass tofunc(). That’s a safe and normal conversion sinceBpublicly inherits fromA.