Mail Archives: cygwin-developers/2002/09/30/02:47:30
Hi!
Sunday, 29 September, 2002 Robert Collins rbcollins AT cygwin DOT com wrote:
>> Now, in verifyable_object_isvalid you're casing pointer to variable of
>> subclass to pointer to base class. Ain't it case of 'never do like
>> this'? I suppose to safely perform cast from subclass to base class
>> one should always use dynamic_cast().
RC> It's a case of this is always ways ok to do - upcasting is FINE.. (it
RC> happens every time you call a virtual function in fact).
Yes, it's fine as long as it's done via compiler. When virtual
function is called it's compiler duty to arrange things so that this
is pointing to the proper place in memory. The same for dynamic_cast,
compiler knows how to update pointer. But what's done in
verifyable_object_isvalid() is _not_ upcasting. It's essentially a
pointer arithmetic. And i bet it's not guaranteed to work -- it will
obviously fail in the case of multiple inheritance when class C is
derived from class A and class B, and clearly, you won't be able to do
the trick with pointer assignments to cast pointer to the instance of
class C to both class A and class B. You'll need to use compiler
knowledge about class C instance layout for either casting to class A
or class B. So, the safe way is to always use dynamic_cast (or virtual
functions) and let compiler to arrange everything.
RC> It's never ok to case a base class to a subclass (known as downcasting)
RC> unless you use a static_cast or a dynamic_cast.
RC> http://www.cs.rpi.edu/~wiseb/xrds/ovp3-1.html
That document doesn't say that you can safely do pointer arithmetic to
cast from derived class to the base.
RC> What *may* be a regression in 3.2 is the apparent bug caused by the
RC> introduction of a VMT in a derived class. However, as we already have a
RC> destructor for verifyable_object, and in this instance it should be
RC> virtual, we get to sidestep the bullet - for now.
Which bug in gcc? I guess we should look into C++ standard first. But
i suspect it doesn't say anything about offsets for common members in
base and derived classes being always equal, so that programmer can do
pointer assignment to cast from base to derived and vice versa. As i
said, it wouldn't be true in at least one case -- multiple
inheritance. So, before qualifying this as a gcc bug, you should first
give an appropriate reference to the standard.
Egor. mailto:deo AT logos-m DOT ru ICQ 5165414 FidoNet 2:5020/496.19
- Raw text -