Inheritance & Derivation

Source: Internet
Author: User
Tags access properties

I. What is inheritance and derivation

Encapsulation, inheritance, polymorphism are three important features of C + +. In object-oriented technology, the reusability of software is emphasized, and the inheritance mechanism is used to solve the problem of reusing software. In C + +, the so-called "inheritance" is the creation of a new class on the basis of an already existing class. A class that already exists becomes the base class or parent class, and the newly created class is called a derived class or subclass.

A class obtains an existing attribute from an existing class, which is called inheritance of a class. With inheritance, a new subclass obtains the attributes of the parent class from the parent class. From another perspective, a new Class (subclass) is generated from the existing class (the parent Class), called the derivation of the class. Derived classes inherit all data members and member functions of the class base and can make the necessary adjustments to the members. A base class can derive multiple derived classes, and each derived class can then derive a new derived class as a base class. Therefore, the base class and the derived class are relative. Each derivation of a class inherits the basic characteristics of its base class, while making new adjustments as needed. A derived class derives from only one base class, which is called single inheritance. A derived class also has two or more base classes, such as multiple inheritance. The relationship between a base class and a derived class can be understood as: The base class is an abstraction of a derived class, and a derived class is a materialization of the base class.


Ii. How derived classes are declared

Declares a generic form of a single-inheritance derived class:

Class derived class Name: Inheritance mode base class name

{

Newly added members of derived classes

};

There are three ways of inheriting: public (Common), protected (protected), private. This entry defaults to private if it is not written.

Example: Suppose a base class has been declared time, on which a derived class is declared by a single inheritance date

Classdate:publictime//Common inheritance

{

Public

Voiddisplay ()

{

cout << _year << _month << _day << Endl;

}

Private

Int_year;

Int_month;

Int_day;

};


Iii. composition of derived classes

The members of a derived class include the members that inherit from the base class and the two most of the members you add themselves. It does not mean, however, that simply adding the members of the base class and the members of the derived class together is a derived class. Constructing a derived class consists of the following 3 parts:

1. Accept members from the base class

Derived classes accept all members of the base class (excluding constructs and destructors). It is not optional to accept part and discard another part. Therefore, if the base class cannot be chosen rationally, it will result in redundancy of the data.

2. Adjust the members received from the base class

Although accepting base class members is not optional, you can make adjustments to these members, such as inheritance, to change the access properties of base class members in derived classes. In addition, a member with the same name as a base class member can be declared in a derived class, and a new member in a derived class overrides a member of the same name in the base class. Note that if you are a member function, you need not only the same function name, but also the parameter list of the function.

3. Add a new member to a derived class

The base class simply provides the most basic functionality, and some features are not implemented, so you need to include some specific functionality when declaring a derived class to form a derived class for a particular application. In addition, when declaring derived classes, there is generally a definition of constructors and destructors that apply to derived classes.


Iv. access properties for derived class members

1. Base class member functions can access only base class members

2. Derived class member functions can access the added members of derived classes themselves

3. The member function of the base class cannot access the newly added members of the derived class.

4. The derived class member function accesses the members of the base class within a class or outside the class, which is more complex, depending not only on the access properties of the base class members in the base class, but also on the inheritance of the base class as declared by the derived class.

650) this.width=650; "Src=" http://img.blog.csdn.net/20160722170423998?watermark/2/text/ Ahr0cdovl2jsb2cuy3nkbi5uzxqv/font/5a6l5l2t/fontsize/400/fill/i0jbqkfcma==/dissolve/70/gravity/center "/>


650) this.width=650; "src="/e/u261/themes/default/images/spacer.gif "style=" Background:url ("/e/u261/lang/zh-cn/ Images/localimage.png ") no-repeat center;border:1px solid #ddd;" alt= "Spacer.gif"/>

As you can see from the table above, there are 4 different access properties in the derived class:

1. Public, accessible within derived classes and outside of derived classes.

2, protected, derived classes can be accessed, outside the derived class can not be accessed.

3, private, can only be accessed within the derived class.

4, inaccessible, or not directly accessible, can be accessed indirectly through the base class member function.


V. Constructors for derived classes

Because constructors and destructors for base classes cannot be inherited, the initialization of inherited base class members is assumed by the constructor of the derived class, so the constructor of the base class is called when the constructor of the derived class is executed. The general form is:

Derived class constructor name (General Staff): base class constructor Name (parameter list)

{Newly added data member initialization statement} in derived class}


Initialization of a base class member is initialized by the initialization list. The General Staff list contains the parameters required by the base class constructor and the parameters required to initialize the derived class's data members. The argument list that follows the base class constructor name does not include the parameter type, because it is called the constructor of the base class, which is the argument.

Cases:

Classtime

{

Public

Time (inthour= 0,intminute= 0,intsec= 0): _hour (hour)

, _minute (minute)

, _sec (SEC)

{

}

Private

Int_hour;

Int_minute;

Int_sec;

};



Classdate:publictime

{

Public

Date (inthour= 0,intminute= 0,intsec= 0,intyear= 0,intmonth= 0,intday= 0): Time (HOUR,MINUTE,SEC) Call the constructor of the base class to initialize the base class member

{

_year =year;

_month =month;

_day =day;

}

Private

Int_year;

Int_month;

Int_day;

};

There are derived classes with child objects, and the same method is used for child object initialization.


So a derived class constructor should contain 3 parts:

1. Initialize the base class data member

2, child object initialization

3. Initialize the derived class data member.


The constructor of the base class is automatically called by the system, and the constructor of the derived class is written in the way that it is only for the constructor of the base class, if it is not written in the form above, the system will call the default constructor of the base class (the sub-object is also the same reason). The system first calls the constructor of the base class and then executes the constructor of the derived class.


Vi. destructors in derived classes

We just need to define the constructors for the new members in the derived class. The destructor of the base class and the destructors for the sub-objects are automatically called by the system. The order in which the destructors are called is reversed from the order in which the constructors are called, and the destructor of the base class is then called by the constructor of the derived class.


Vii. Multiple Inheritance

Multiple inheritance: Running a derived class inherits multiple base classes at the same time.

1. Methods of declaring multiple inheritance

Example: If you have declared Class A, Class B, and Class C, you can declare a derived class D of multiple inheritance:

Class D:private a,protected b,public C

{New member of Class D};

D is a derived class of multiple inheritance that inherits Class A as a private inheritance, inherits Class B in a way that protects inheritance, inherits Class C in a way that is common inheritance.


2. Constructors for multiple inheritance derived classes

A multiple-inheritance derived class has the same constructor form as a single-inherited constructor, except that it contains multiple base class constructors in the initialization table. Such as:

Derived class constructor names (General Staff list): base class 1 Constructors (argument lists), base class 2 constructors (argument list) ...

{New data member initialization statement} in derived class};


3. Problems caused by multiple inheritance

Multiple inheritance raises the question of ambiguity, that is, if the inherited member has the same name, then the reference will produce two semantics and an error occurs.

Example: If both Class A and Class B have data member name and member function display. If Class C is a direct derived class of Class A and Class B.

If in the main function there are:

C C1;

C1.name;

C1.display ();

Because both Class A and Class B have data member name and member function display, the system cannot discriminate which base class members are to be accessed, so there is an error compiling. To work around this problem, you can use the base class name to limit the scope:

C1. A::name;

C1.     A::d isplay (); This means that references to members in Class A are referenced.


Eight, virtual base class

If a derived class has more than one direct base class, these direct base classes have a common base class.

650) this.width=650; "Src=" http://img.blog.csdn.net/20160722170453499?watermark/2/text/ Ahr0cdovl2jsb2cuy3nkbi5uzxqv/font/5a6l5l2t/fontsize/400/fill/i0jbqkfcma==/dissolve/70/gravity/center "/>

650) this.width=650; "src="/e/u261/themes/default/images/spacer.gif "style=" Background:url ("/e/u261/lang/zh-cn/ Images/localimage.png ") no-repeat center;border:1px solid #ddd;" alt= "Spacer.gif"/>

Then there will be a problem, in Class E will save 3 members of Class A, if people only need a member of Class A, then this situation will occupy more memory space, but also increase the difficulty of access. In practice, people often only need a member of Class A. To solve this problem, the virtual base class method is provided in C + +, so that only one member is retained when inheriting the indirect common base class.

Now declare Class A as a virtual base class:

Class A

{...};

Class B:virtual public A//a is the virtual base class of B

{...};

Class C:virtual public A//a is the virtual base class of C

{...};

Class D:virtual public A//a is the virtual base class of D

{...};

Note: The virtual base class is not declared when the base class is declared, but when the derived class is declared, when the inheritance method is specified.



The general method for declaring a virtual base class is as follows:

Class Derived classes Name: Virtual Inheritance Mode base class name


After the declaration of a virtual base class, when the base class is inherited by a derived class through multiple derived paths, the derived class value inherits the derived class one time, that is, the base class member derived class is reserved only once.


1. Initialization of virtual base class

Class A

{

A (int i=0) {}

...};


Class B:virtual public A//a is the virtual base class of B

{

B (int j=2): A (j) {}

...};


Class C:virtual public A//a is the virtual base class of C

{

C (int k=3): A (k) ()

...};


Class D:virtual public A//a is the virtual base class of D

{

D (int n=4): A (n) {}

...};


Class E:public B,public c,public D

{

E (int i=0,int j=0,int k=0,int n=0): A (i), B (j), C (k), D (n) {}

...};


Attention:

When defining a constructor for Class E, it differs from the method used previously, because the virtual base class has only one copy of the data member in the derived class, so the data member must be given between the derived classes. Rule: In the last derived class, it is not only the responsibility to initialize the base class between them, but also the initialization of the virtual base class. The C + + compilation system only performs calls to the constructors of the virtual base class from the last derived class, ignoring calls from other derived classes of the virtual base class to the virtual base class constructor.


Ix. transformation of base class and derived class

A derived class is a data member that inherits from a base class, and if there is an assignment relationship between the base class object and the derived class object, can the type be converted???

The answer is yes. There is an assignment-compatible relationship between the base class object and the derived class object, because the derived class contains members that inherit from the base class, so you can assign the value of the derived class to the base class object, which can be overridden with the derived class object when using the base class object. But note that this relationship is unidirectional and irreversible.


The following 4 aspects are specific:

1. A derived class object can assign a value to a base class object, which is one-way.

2. A derived class object can be used to assign or initialize a reference to a base class object instead of a base class object.

3. If the parameter of a function is a reference to a base class object or a base class object, the corresponding argument can be an object of the derived class.

4. The address of a derived class can be assigned to a pointer to a base class object. The pointer to the base class can point to the object of the derived class. However, it points to the part of the derived class object that inherits from the base class.


This article from the "11132019" blog, reproduced please contact the author!

Inheritance & Derivation

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.