Home > Backend Development > C++ > body text

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

Mary-Kate Olsen
Release: 2024-10-28 04:42:02
Original
275 people have browsed it

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>
Copy after login

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>
Copy after login

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>
Copy after login

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!