Objects (object) are an instance of Class (Instance). If the object is compared to a house, then class is the design drawing of the house. So the focus of object-oriented design is class design, not object design. For C + + programs, it is easy to design orphaned classes, and it is difficult to design base classes and their derived classes correctly. This chapter only deals with the concepts of "inheritance" (inheritance) and "combination" (composition).
Note that the current application of object-oriented technology is COM and CORBA, which is beyond the scope of C + + textbooks, please read COM and CORBA related works.
10.1 Inheritance
If a is a base class, B is a derived class, then B inherits the data and functions of a. For example:
Class A
{
Public
void Func1 (void);
void Func2 (void);
};
Class B:public A
{
Public
void Func3 (void);
void Func4 (void);
};
Main ()
{
b b;
B.func1 (); b inherits the function from a Func1
B.FUNC2 (); b inherits the function from a FUNC2
B.func3 ();
B.func4 ();
}
This simple example program illustrates the fact that the "inheritance" attribute of C + + can improve the reusability of programs. Because inheritance is too useful and easy to use, it is important to prevent "inheritance" from being used indiscriminately. We should make some rules for the use of "inheritance".
L "Rule 10-1-1" if Class A and Class B are irrelevant, you cannot allow B to inherit A's functionality and properties in order to make B more functional. Do not feel "free to eat", so that a healthy young people eat ginseng to fill the body without a reason.
L "Rule 10-1-2", if logically B is "one" (a kind of) of a, allows B to inherit the functions and properties of a. For example, a man is a man (Human), and a Boy (Boy) is a man. Then the class man can derive from the class human, and the class boy can derive from the class man.
Class Human
{
...
};
Class Man:public Human
{
...
};
Class Boy:public Mans
{
...
};
U Note matters
"Rule 10-1-2" looks simple, but it can be unexpected when applied, and the concept of inheritance is not exactly the same in the world of the program as in the real world.
For example, from the biological point of view, ostriches (ostrich) is a bird (Bird) is a kind of, by theory, class ostrich should be able to derive from the class Bird. But the ostrich can't fly, so what is Ostrich::fly?
Class Bird
{
Public
virtual void Fly (void);
...
};
Class Ostrich:public Bird
{
...
};
For example, in mathematical terms, a circle (Circle) is a special ellipse (Ellipse), which logically says that class Circle should be derived from class Ellipse. But the ellipse has a long axis and a short axis, if the circle inherits the ellipse's long axis and the short axis, does not gild the lily?
So the more stringent inheritance rule should be: If logically B is "one" of a, and all functions and properties of a have meaning for B, then B is allowed to inherit the functions and properties of a.