Conversion of Derived Class Double Pointers to Base Class Double Pointers: Anonymity and Safety
In C , pointers to derived classes can be implicitly converted to pointers to their base classes, which is a convenient feature for inheritance-based programming. However, when it comes to double pointers, this implicit conversion raises some safety concerns.
Consider the following code:
<code class="cpp">class Base { }; class Child : public Base { }; int main() { // Convert child to base (no problem) Child *c = new Child(); Base *b = c; // Convert double pointer to child to double pointer to base (error) Child **cc = &c; Base **bb = cc; // error: invalid conversion from ‘Child**’ to ‘Base**’ }</code>
GCC rightfully complains about the last assignment statement because the direct conversion from Child** to Base** is not allowed implicitly. This is due to a fundamental difference in the nature of these pointers:
Allowing Child** to implicitly convert to Base** would violate this distinction and introduce potential safety hazards:
<code class="cpp">// After explicit cast *bb = new Base; // Child pointer now points to a Base!</code>
This could lead to object slicing, where the Child-specific data would be lost and integrity compromised. To maintain type safety, the conversion between Child** and Base** is explicitly forbidden.
Alternative Casting Options
While implicit casting is not supported, there are alternative casting methods that allow interconversion between derived class and base class double pointers:
In summary, the lack of implicit conversion between derived class double pointers and base class double pointers protects against potential type safety issues. When necessary, use alternative casting methods with caution and consider modifying class definitions for dynamic casting with virtual destructors.
The above is the detailed content of Can Derived Class Double Pointers Be Implicitly Converted to Base Class Double Pointers in C ?. For more information, please follow other related articles on the PHP Chinese website!