Home > Backend Development > C++ > Why is Implicit Conversion from `Child` to `Base` Forbidden in C Inheritance?

Why is Implicit Conversion from `Child` to `Base` Forbidden in C Inheritance?

DDD
Release: 2024-10-28 16:10:28
Original
414 people have browsed it

 Why is Implicit Conversion from `Child` to `Base` Forbidden in C   Inheritance?

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

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

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.

  • Virtual Inheritance: With virtual inheritance, a class inherits from multiple parent classes through a single copy of the base class object. This can be used to achieve polymorphic behavior without the aforementioned conversion issues.
  • Bridge Classes: One can define an intermediate class that inherits publicly from both Base and Child and serves as a bridge between the two. This allows for explicit and controlled casting between the different pointer types while maintaining 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!

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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template