-1

Does order matter when casting and does this have an effect on freeing an object with a virtual base class? E.g. if you upcasted 2 levels, must you downcast 2 levels, or can you downcast 1 level at a time?

struct A {
    virtual ~A() = default;
    ...
};
struct A_Extra : A {...};

struct B : A_Extra {...};

std::vector<A*> data;

void scenario1() {
    // create sample object - incremental upcasting
    A_Extra* b = new B();
    data.push_back(b);

    A* a = data.front();
    // which one(s) of these casts are valid ?
    B* option1 = static_cast<B*>(static_cast<A_Extra*>(a));
    B* option2 = static_cast<B*>(a);

    // which one(s) of these frees are valid ?
    delete a;
    delete static_cast<A_Extra*>(a);
    delete static_cast<B*>(static_cast<A_Extra*>(a));
    delete static_cast<B*>(a);
}

void scenario2() {
    // create sample object
    B* b = new B();
    data.push_back(b);

    A* a = data.front();
    // which one(s) of these casts are valid ?
    B* option1 = static_cast<B*>(static_cast<A_Extra*>(a));
    B* option2 = static_cast<B*>(a);

    // which one(s) of these frees are valid ?
    delete a;
    delete static_cast<A_Extra*>(a);
    delete static_cast<B*>(static_cast<A_Extra*>(a));
    delete static_cast<B*>(a);
}
DaE-Asew
  • 137
  • 1
  • 7

1 Answers1

4

Does order matter when casting

Yes, order matters when casting.

does this have an effect on freeing ...

None of your shown casts have an effect.

... with a virtual base class?

None of your classes have a virtual base class.

E.g. if you upcasted 2 levels, must you downcast 2 levels, or can you downcast 1 level at a time?

You can upcast and downcast multiple levels at once, and you can downcast less than you have upcasted.


// which one(s) of these casts are valid ?

Both are valid.

// which one(s) of these frees are valid ?

All of them are valid (as long as only one of them is used).

Answers apply to both screnarios.

Casts to B* and A_Extra* are potentially dangerous because the A* might not point to an object of such type. In these scenarious they do, and if you can guarantee that, then the cast is valid. In cases where that can not be guaranteed, dynamic_cast is a safer alternative.

Regardless, all of the casts in both scenarios are redundant. It's best to not use casts that are unnecessary.

eerorika
  • 232,697
  • 12
  • 197
  • 326