Diamond inheritance (diamond problem) and diamond Inheritance Problem Diamond

Source: Internet
Author: User

Diamond inheritance (diamond problem) and diamond Inheritance Problem Diamond

When learning C ++, diamond inheritance is definitely an inevitable key issue. What is Diamond inheritance? Is it like a diamond? It's really ugly to draw pictures.

Because C ++ allows multi-inheritance, this will happen when the inheritance relationship is like this.

Class A is A base class, and Class B contains A, I represent B (A), and class C contains A, I represent C ()

Then there are B and C in D, which I represent as D (B (A) C ())

When we want to use A in D, or access A's part score, we can explain which A actually belongs to D, is A in d B A or A in C?

1 class A 2 {}; 3 class B: public A4 {}; 5 class C: public A6 {}; 7 class D: public B, public C8 {};

This can be an error. Some compilers won't even let you pass it and report an error directly to you.

This is embarrassing, isn't it? Even if the compilation phase passes you, don't try to access its internal A object through the D object like this, which will make the compiler very tangled

But it's easy to give a vitual.

1 class A 2 {}; 3 class B: virtual public A4 {}; 5 class C: virtual public A6 {}; 7 class D: public B, public C8 {};

He has his own A. when calling the variables or functions in A, he will call them in his own A, so that he will not tangle the compilation period.

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.