Home  >  Article  >  Backend Development  >  Why Can\'t We Implicitly Convert a Pointer-to-Pointer to a Base Class in C ?

Why Can\'t We Implicitly Convert a Pointer-to-Pointer to a Base Class in C ?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-10-28 04:42:02276browse

Why Can't We Implicitly Convert a Pointer-to-Pointer to a Base Class in C  ?

Implicit Conversion of Pointer-to-Pointer Between Derived and Base Classes

In C , the following code raises an error:

<code class="cpp">Child **cc = &c;
Base **bb = cc;</code>

The error message indicates that there is no implicit conversion from Child** to Base**. However, it is allowed to assign a child pointer to a base pointer:

<code class="cpp">Child *c = new Child();
Base *b = c;</code>

To understand why this difference exists, consider what would happen if the implicit conversion were allowed. One could then do the following:

<code class="cpp">*bb = new Base;</code>

This would result in c pointing to an instance of Base, which would violate the concept of derived and base classes. Therefore, C prohibits this implicit conversion.

To allow the assignment between Child** and Base**, one can use C-style casts or reinterpret_cast, but they sacrifice type safety. There is no way to achieve this conversion with an implicit cast or static_cast.

The above is the detailed content of Why Can\'t We Implicitly Convert a Pointer-to-Pointer to a Base Class in C ?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn