Conversion of Pointer-to-Pointer in Inheritance Hierarchy
Consider the following C code:
<code class="cpp">class Base { }; class Child : public Base { }; int main() { Child *c = new Child(); Base *b = c; // Allowed Child **cc = &c; Base **bb = cc; // Error: Conversion not allowed }</code>
Rationale for Conversion Restriction
The compiler error in the last line highlights the restriction on implicit conversion from Child** to Base**. This restriction is imposed to maintain type safety.
If this conversion were allowed, it could potentially lead to unexpected and erroneous situations. For instance, one could write:
<code class="cpp">*bb = new Base;</code>
This would create an instance of Base and store its address in bb, effectively overwriting the original Child* reference pointed to by c. This could lead to data corruption and unpredictable program behavior.
Alternatives for Implicit Conversion
While there is no direct way to implicitly cast Child** to Base** without relying on C-style or reinterpret_cast, there are alternative approaches to achieve the desired functionality while preserving type safety.
The above is the detailed content of Why is Implicit Conversion from `Child` to `Base` Forbidden in C Inheritance?. For more information, please follow other related articles on the PHP Chinese website!