parts/6.44.PolymorphicVariables-BKK.md

6.44 Polymorphic variables [BKK]

6.44.1 Applicability to language

This vulnerability as described in ISO/IEC TR 24772-1:2019 applies to C++. In addition to the upcast and downcast issues addressed in that document, this clause also addresses cross-casting, which is unique to C++. For further type system related issues see subclause Type System[IHN].

C++ provides language mitigations to help avoid the problems as follows:

Since C++ supports multiple inheritance, up-casting, down-casting, and cross-casting operations can be used to switch to different (pointer/reference) types in the inheritance hierarchy of a specific object, i.e.,

Developers should be aware that virtual member functions can be overridden in derived classes, even if they are private.

Given the following:

struct Z { int z; virtual ~Z() { } };
struct Y { int y; virtual ~Y() { } };
struct A : Z { int a; };
struct B : virtual A { int b; };
struct C : virtual A, Y { int c; };
struct D : B, C { int d; };
D d_inst;

then these examples demonstrate upcasts, downcasts, and crosscasts:

Upcasts:

B* b_ptr = &d_inst; // implicit
C& c_ref = d_inst; // implicit
Z* z_ptr = static_cast<Z*>(&d_inst);
Y* y_ptr = dynamic_cast<Y*>(&d_inst);

Downcasts:

D& d_ref = dynamic_cast<D&>(*y_ptr);
D* d_ptr = static_cast<D*>(b_ptr);

Crosscasts:

C* c_ptr = dynamic_cast<C*>(b_ptr);
Y* y_ptr2 = dynamic_cast<Y*>(b_ptr);
C* c_ptr = static_cast<C*> (static_cast<D*>(b_ptr));

and notes the following about such:

Upcasts:

Downcasts

Crosscasts:

Deleting derived objects via a base class pointer is undefined behavior, unless the base class declares a virtual destructor.

6.44.2 Avoidance mechanisms for language users

To avoid the vulnerability or mitigate its ill effects, C++ software developers can:

See also C++ Core Guidelines ES.48, ES.49, C.146, C.147, C.148 and C.153. source: OOP52-CPP?