Implicit Conversion of Pointer-to-Pointer between Derived and Base Classes
When dealing with pointer-to-pointer conversions between derived and base classes, a common error encountered is the inability to implicitly convert a pointer-to-pointer of the derived class (Child) to a pointer-to-pointer of the base class (Base). This is because such a conversion can lead to unexpected and potentially dangerous situations.
Consider the example program provided:
<code class="cpp">class Base { }; class Child : public Base { }; int main() { Child *c = new Child(); Base *b = c; Child **cc = &c; Base **bb = cc; // error: invalid conversion from ‘Child**’ to ‘Base**’ }</code>
The error arises because the compiler prevents the assignment of cc (a Child) to bb (a Base). This underlying reason for this prohibition is to safeguard against potential inconsistencies in the object pointed to by bb. If such a conversion were allowed, it could lead to a scenario where bb points to an instance of Base that is not derived from Child.
To address this issue, there are two approaches:
The above is the detailed content of Why Can\'t You Implicitly Convert a Pointer-to-Pointer of a Derived Class to a Pointer-to-Pointer of a Base Class?. For more information, please follow other related articles on the PHP Chinese website!