Chapter 3 inheritance and combination of Classes

Source: Internet
Author: User

10.1 inheritance

C ++'s "inheritance" feature can improve program reusability. Because "inheritance" is too useful and easy to use, it is necessary to prevent the misuse of "inheritance ". We should set rules for "inherit.


[Rule 10-1-1] If Class A and Class B are irrelevant, B cannot inherit the functions and attributes of a to make B more functional.Do not think that "white food, white food, and white food" makes a good and strong young man have no choice.

People who eat ginseng to make up their bodies.

[Rule 10-1-2] If B is logically a kind of A, B is allowed to inherit the functions and attributes of.For example, a man is a human, and a boy is a man.

Class man can be derived from class human, and class boy can be derived from class man.

A more strict inheritance rule should be: If B is logically A, and all functions and attributes of a are meaningful to B, B is allowed to inherit the functions and attributes of.



10.2 combination


[Rule 10-2-1] logically, if A is a part of B, B cannot be derived from a. Instead, B must be combined with other things.

For example, eye, nose, mouth, and ear are part of the head, therefore, class head should be composed of class eye, nose, mouth, and ear, not derived.

If the head is allowed to be derived from eye, nose, mouth, and ear, the head will automatically have functions such as look, smell, eat, and listen. Example 10-2-2 is very short and runs correctly, but this design method

It is wrong.

// The function is correct and the code is concise, but the design method is incorrect.

Class head: Public Eye, public nose, public mouth, public ear



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: 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.