C + + Virtual base class

Source: Internet
Author: User

Naming conflicts can easily arise when multiple inheritance occurs, and if we carefully name the member variables and member functions in all classes as different names, it is still possible for a naming conflict to occur, such as a very classic diamond inheritance hierarchy. Class A derives from Class B and Class C, and Class D inherits from Class B and Class C, at which time the member variables and member functions in Class A inherit into Class D into two parts, one from a derived B and then the other from a derivation C, and then the derivation of D.

Connotation of the Satin update

Thunder Member No. 11th share

Music View Members Share

This example is a typical diamond inheritance structure, the member variables in Class A and the member functions inherit into Class D will produce two copies, such a naming conflict is very tricky, through the domain resolution operator has been unable to distinguish the specific variables. For this reason, C + + provides virtual inheritance in this way to resolve the naming conflict problem. Virtual inheritance requires only the virtual keyword to precede the inherited attribute.

Example 2:

2015 high-score action movies

In this case, Class B and Class C are both inherited and class A are virtual, and after doing so, Class D will only get a copy of the data from Class A. In the main function of this example, the object test of Class D is defined, and then the SETX and GETX member functions are called indirectly from Class A, since B and C inherit from Class A with virtual inheritance, so calling Setx and getx through D does not have a naming conflict problem. Because Class D only gets a copy of A's data.

FREE Membership

C + + Virtual base class

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.