Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Should I expect that upcasts and downcasts in single inheritance don't adjust the pointer?

Suppose I have:

class Base {
public:
    virtual void Nothing() {}
};
class MiddleDerived : public Base {
    virtual void Nothing() {}
};
class Derived : public MiddleDerived {
    virtual void Nothing() {}
};

and my code goes like this:

Derived* object = new Derived();
Base* base = object; //implicit conversion here

void* derivedVoid = object;
void* baseVoid = base;

Should I expect that baseVoid == derivedVoid?

I know that most implementations work this way but is it guaranteed?

like image 301
sharptooth Avatar asked Sep 25 '22 14:09

sharptooth


2 Answers

What you "should expect" can be different from what's guaranteed.

A static_cast up or down an inheritance chain can change the address.

The canonical example where this occurs in practice is where a base class is non-polymorphic and a derived class introduces some virtual function, which with many compilers then introduce a vtable pointer at the start of each derived object.

like image 133
Cheers and hth. - Alf Avatar answered Oct 23 '22 18:10

Cheers and hth. - Alf


I think the part of the standard that deals with this is §5.2.9 (13)

Which states (in a nutshell) that a T* cast to a void* and then back to a T* shall refer to the same object.

However there is no stipulation The address of Derived must be the same as the address of its Base.

So my answer would be, "no - code that expects this equivalency is ill-formed inviting undefined behaviour".

like image 26
Richard Hodges Avatar answered Oct 23 '22 19:10

Richard Hodges