5

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?

sharptooth
  • 167,383
  • 100
  • 513
  • 979
  • Consider substituting "language lawyer" for "portability"? โ€“ Bathsheba Jan 25 '16 at 13:41
  • As you phrased the question (rather than the example) you left open the possibility that the base class might not have any virtual methods (while some derived class does). That could still be "single inheritance" but the pointers would **not** be equal. For your **example**, I'm not a good enough language lawyer to back up my belief that it is true only in common practice, not promised by the standard. โ€“ JSF Jan 25 '16 at 13:41
  • I think this should work but I don't think there is a standard layout for non POD classes. โ€“ NathanOliver Jan 25 '16 at 13:50

2 Answers2

2

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.

Cheers and hth. - Alf
  • 142,714
  • 15
  • 209
  • 331
2

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".

Richard Hodges
  • 68,278
  • 7
  • 90
  • 142