Diamond inheritance relationship

Source: Internet
Author: User

 

 

 

Consider this situation:

Class ca {};

Class CB: public CA {};

Class CC: public CA {};

 

In this case, we need a CD class that inherits both CB and CC.

The problem arises.

If we write:

Class CD: Public CB, public CC {};

 

When constructing a CD class,

The result is as follows:

 

That is, a CD class has two CAS (its superclass)

This is unreasonable. Fuzzy call will occur.

 

How can this problem be avoided?

Virtual inheritance is useful.

 

We need to rewrite the Inheritance Method of CB and CC.

Class CB: Public ‑el ca {};

Class CC: Public Virtual ca {};

 

Others do not need to be modified. When we construct a CD class,

The order is as follows:

Start to construct the CD class,

First construct a super-class Ca, and then construct CB,

Construct CC (parent class CA of CC will not be constructed at this time)

In this way,

The CB and CC contained in the CD object will share the same CA object.

 

In this case, fuzzy calling will not occur.

 

----------------------------------- Lili split line --------------------------------------

 

This is C ++'s notorious multi-inheritance.

This does not happen in Java,

If you must use the diamond inheritance, you can use virtual inheritance.

If your project has too many diamond inheritance,

Maybe you should review your software engineer.

 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.