Is it safe to downcast objects (not pointers) to their known derived type?

John picture John · Feb 14, 2012 · Viewed 7.7k times · Source

Would there be a danger of slicing

result Compare(const Osp::Base::Object &obj1, const Osp::Base::Object &obj2, int &cmp) const {
    cmp = ((const Block)obj1).NumSuperBlocks() - ((const Block)obj2).NumSuperBlocks();
}

Where

class Block : Object {/*Filler*/}

and obj1 and obj2 are assured to be Block objects?

I'm tempted to use:

    cmp = ((const Block*)&obj1)->NumSuperBlocks() - ((const Block*)&obj2)->NumSuperBlocks();

but on reading SO's brief description of the object-slicing tag I'm tempted to use the former. But I really don't want any nasty silent slicing.

Answer

Ben Voigt picture Ben Voigt · Feb 14, 2012

References and pointers are both polymorphic.

You may prefer

static_cast<const Block&>(obj1).NumSuperBlocks()

for downcasting starting with a reference, it's equivalent to *static_cast<const Block*>(&obj1).