On which lines of code will compilation errors occur?
class B {
    virtual void f() {}
};

class V {
    virtual void g() {}
};

class X {
};

class D : public B, virtual public V, virtual public X {
};

int main() {
    D d;

    B* pb = &d;
    D* p1 = (D*)pb;                // 1
    D* p2 = dynamic_cast<D*>(pb);        // 2

    V* pv = &d;
    D* p3 = (D*)pv;                // 3
    D* p4 = dynamic_cast<D*>(pv);        // 4

    X* px = &d;
    D* p5 = (D*)px;                // 5
    D* p6 = dynamic_cast<D*>(px);        // 6

    return 0;
}
Explanation
The compiler cannot generate code to cast from the base type to the derived if the inheritance is virtual. This is because the subobject of the virtual base class inside the descendant class object cannot calculate the address of the enclosing object at the compilation stage. But this address can be calculated at the execution stage and, therefore, such a cast can be performed by the dynamic_cast operator.
By answer options:
1. Correct, correctness is not checked
2. Correct, checked at run-time
3. Error: cast from a virtual base class. Not enough information to cast.
4. Correct. Done in runtime. There is enough information.
5. Error: cast from a virtual base class. Not enough information to cast.
6. Error: cast from a non-polymorphic base class. There is no type information on the px pointer.

Следи за CodeGalaxy

Мобильное приложение Beta

Get it on Google Play
Обратная Связь
Cosmo
Зарегистрируйся сейчас
или Подпишись на будущие тесты