2023-05-03 11:06:20 +02:00
== Why is this an issue?
2023-09-18 13:40:16 +02:00
Casting from a virtual base to a derived class, using any means other than `dynamic_cast` has undefined behavior. The behavior for `dynamic_cast` is defined.
2021-04-28 16:49:39 +02:00
2023-09-18 13:40:16 +02:00
Note: As of {cpp}17, the program is considered ill-formed, and an error is reported.
2021-04-28 16:49:39 +02:00
Most compilers emit an error for previous versions of {cpp} as well.
2021-04-28 18:08:03 +02:00
2023-05-03 11:06:20 +02:00
=== Noncompliant code example
2021-04-28 16:49:39 +02:00
2023-09-18 13:40:16 +02:00
[source,cpp,diff-id=1,diff-type=noncompliant]
2021-04-28 16:49:39 +02:00
----
class B { ... };
class D: public virtual B { ... };
D d;
B *pB = &d;
2023-09-18 13:40:16 +02:00
D *pD1 = ( D * ) pB; // Noncompliant - undefined behavior
D *pD2 = static_cast<D*>(pB); // Noncompliant - undefined behavior
2021-04-28 16:49:39 +02:00
----
2021-04-28 18:08:03 +02:00
2023-05-03 11:06:20 +02:00
=== Compliant solution
2021-04-28 16:49:39 +02:00
2023-09-18 13:40:16 +02:00
[source,cpp,diff-id=1,diff-type=compliant]
2021-04-28 16:49:39 +02:00
----
class B { ... };
class D: public virtual B { ... };
D d;
B *pB = &d;
D *pD1 = dynamic_cast<D*>(pB); // Compliant, but pD2 may be NULL
D & D2 = dynamic_cast<D&>(*pB); // Compliant, but may throw an exception
----
2021-04-28 18:08:03 +02:00
2023-05-03 11:06:20 +02:00
== Resources
2021-04-28 16:49:39 +02:00
* MISRA {cpp}:2008, 5-2-2 - A pointer to a virtual base class shall only be cast to a pointer to a derived class by means of dynamic_cast.
2021-04-28 18:08:03 +02:00
2021-06-02 20:44:38 +02:00
2021-06-03 09:05:38 +02:00
ifdef::env-github,rspecator-view[]
2021-06-08 15:52:13 +02:00
'''
2021-06-02 20:44:38 +02:00
== Comments And Links
(visible only on this page)
2023-05-25 14:18:12 +02:00
=== is duplicated by: S869
2021-06-03 09:05:38 +02:00
endif::env-github,rspecator-view[]