[C ++ primer] Chapter 1 class inheritance

Source: Internet
Author: User

1. class inheritance

Definition: a new class is derived from an existing class, and the derived class inherits the features of the original class, including methods.

Objective: To provide reusable code

2. A simple base class

<Strong> # include <iostream> <br/> # include <cstring> <br/> using namespace STD; <br/> class student // base class <br/>{< br/> PRIVATE: <br/> char name [20]; <br/> int num; <br/> int age; <br/> Public: <br/> Student (const char * m_name, const int m_num, const int m_age); <br/> ~ Student (); <br/> virtual void display (); // If a derived class is overloaded, the virtual function is used. <br/>}; <br/> class graduate: public student // note writing of the derived class <br/>{< br/> PRIVATE: <br/> char major [20]; <br/> int thesis; <br/> Public: <br/> Graduate (const char * m_major, const int m_thesis, student & St); <br/> ~ Graduate (); <br/> void display (); <br/> void setthesis (int I); <br/>}; <br/> Student :: student (const char * m_name, const int m_num, const int m_age) <br/>{< br/> strcpy (name, m_name); <br/> num = m_num; <br/> age = m_age; <br/>}< br/> Student ::~ Student () <br/>{< br/> cout <"student is over" <Endl; <br/>}< br/> void Student: Display () <br/> {<br/> cout <"name:" <name <"\ nnum: "<num <" \ Nage "<age <Endl; <br/>}< br/> Graduate: Graduate (const char * m_major, const int m_thesis, student & St): Student (ST) <br/> {// Note: because a derived class cannot directly use a private member of the base class, therefore, you must use the base class constructor <br/> St. display (); <br/> strcpy (Major, m_major); <br/> thesis = m_thesis; <br/>}< br/> Graduate ::~ Graduate () <br/>{< br/> cout <"graduate is over" <Endl; <br/>}< br/> void Graduate: Display () <br/>{ <br/> cout <"Major:" <major <"\ nthesis:" <thesis <Endl; <br/>}< br/> void Graduate: setthesis (int I) <br/>{< br/> thesis = I; <br/>}< br/> int main () <br/>{< br/> Student ST ("tianshuai", 1, 18); <br/> St. display (); <br/> cout <"**************** \ n "; <br/> graduate Gd ("compuater", 5, ST); <br/> GD. display (); </P> <p> return 0; <br/>}< br/> </strong>Output:<Strong> name: tianshuai <br/> num: 1 <br/> age18 <br/> *************** <br/> name: tianshuai <br/> num: 1 <br/> age18 <br/> Major: compuater <br/> Thesis: 5 <br/> graduate is over <br/> student is over <br/> </strong>

[Overview] 1) the inherited class inherits the Private Members of the base class, but cannot directly access the private members through the inherited class objects.

2) The derived class cannot directly access the base class private member. The derived class constructor must use the base class constructor.

3) features of the derived class constructor: The base class object is first created to create graduate Gd (); the student object is first created

When creating a derived class object, first call the base class constructor, and then call the derived class Constructor

When a derived class Object expires, it first analyzes the derived class and then the base class.

4) The base class object and address cannot be assigned to the derived class.

Student st;

Graduate & GD = sT; // not allow

Graduate * GD = sT; // not allow

If allowed, the base class can access the members of the derived class, but it does not make sense for the base class object to access the members that do not exist in the base class.

St. setthesis (int I) // because the base class does not have this method

3. inherit the ----- is-a relationship

Inheritance Methods: total inheritance, private inheritance, and protection inheritance

A is-a relationship is established for a total of inheritance: The derived class object is also a base class object, which can perform any operation on the base class object or the derived class Object

For example, fruit is a fruit with weight and calories. Banana is a derived class that includes weight and calories. It also adds special banana Members which are generally not used for fruit.

4. multi-state co-Inheritance

Two implementation mechanisms: 1> redefine the base class method in the derived class. 2> Use Virtual Methods

No virtual constructor exists, but virtual destructor of the base class are necessary. See the following example:<Strong> class clxbase {<br/> Public: <br/> clxbase () {cout <"output from the con clxbase! "<Endl ;}; <br/> virtual ~ Clxbase () {cout <"output from the destructor of class clxbase! "<Endl ;}; <br/> virtual void dosomething () {cout <" do something in class clxbase! "<Endl ;};< br/>}; <br/> class clxderived: Public clxbase {<br/> Public: </P> <p> clxderived () {cout <"output from the con clxderived! "<Endl ;}; </P> <p> ~ Clxderived () {cout <"output from the destructor of class clxderived! "<Endl ;}; </P> <p> void dosomething () {cout <" do something in class clxderived! "<Endl ;}; </P> <p >}; <br/> void main () <br/>{< br/> clxbase * Ptest = new clxderived; // The pointer of the base class references the object of the derived class </P> <p> Ptest-> dosomething (); // call the method of the derived class </P> <p> Delete Ptest; <br/>}</strong>Output: Do something in class clxderived!
Output from the destructor of class clxderived!
This is very easy to understand.
However, if you remove the virtual before the clxbase destructor, the output result is as follows:
Do something in class clxderived!
That is to say, the destructor of the class clxderived is not called at all! Under normal circumstances, all the class destructor release the memory resources, and if the Destructor is not called, memory leakage will occur. I think all c ++ programmers know this danger. Of course, if you do other work in the destructor, all your efforts will be in vain.
Of course, it is not necessary to write all class destructor as virtual functions. When there is a virtual function in the class, the compiler will add a virtual function table to the class to store the virtual function pointer, which will increase the storage space of the class. Therefore, only when a class is used as the base class can the Destructor be written as a virtual function.

V. Static and Dynamic Association

Function name association: Interpreting function calls in source code as executing specific function code blocks

However, due to function overloading in C ++, the compiler must check function parameters and function names to determine which function to use.

Static Association: conduct association during compilation

However, virtual functions make this work more difficult. Which function can be used cannot be determined during compilation?

Dynamic concatenation: code that selects the correct virtual method when running the program

1) why are there two types of association? Why is static association the default?

Dynamic Association allows you to redefine the class method, while static Association is poor, but static Association is highly efficient.

If the derived class does not redefine any methods of the base class, dynamic association is not required. Only define the functions that need to be redefined in the derived classes as virtual

2) working principles of virtual functions

The compiler adds a hidden member to each object and stores a pointer to the function address. This array becomes a virtual function table.

When calling a virtual function, view the address of the virtual function table stored in the object and switch to the corresponding function address table. If you use the first virtual function defined in the class declaration, the program uses the first function address in the array and executes the function with this address.

3) Considerations

If you redefine the inherited method, make sure it is exactly the same as the original prototype.

If the base class declaration is overloaded, all base class versions should be redefined in the derived class.

Vi. abstract base classABC (abstract base class)

Note:The public data and methods of several sub-classes are abstracted to form an abstract base class, and then these sub-classes are generated from the abstract base class, you can use the base class pointer array to manage these subclasses at the same time. For different methods in each subclass, you can define this method as a pure virtual function in the abstract base class, and define this method as a virtual function in each subclass. 
# Include <iostream> <br/> using namespace STD; <br/> const double Pi = 3.14; <br/> class baseellipse // abstract base class public member with circle and ellipse <br/>{< br/> PRIVATE: <br/> double X; <br/> double y; <br/> Public: <br/> baseellipse (double t_x = 0, double t_y = 0) <br/>{< br/> X = t_x; <br/> Y = t_y; <br/>}< br/> virtual ~ Baseellipse () {}< br/> void move (int nx, int NY) <br/>{< br/> X = NX; <br/> Y = NY; <br/> cout <"Center Coordinate:" <"(" <x <"," <Y <")" <Endl; <br/>}< br/> <strong> </strong> <PRE name = "code" class = "html"> virtual void area () const = 0; // The End Of The pure virtual function is "= 0", which can be defined only in the class without implementation </PRE> <p>}; Class circle: Public baseellipse // circle {PRIVATE: Double R; public: Circle (double t_x = 0, double
T_y = 0, double t_r = 0); // radius and Center Coordinate circle (const baseellipse & Ba, double t_r = 0); void area () const ;}; class ellipse: public baseellipse // elliptic {PRIVATE: Double A; Double B; public: ellipse (double t_x = 0, double t_y = 0, double T_A = 0, double T_ B = 0 ); ellipse (const baseellipse
& P, double T_A = 0, double T_ B = 0); void area () const ;};/* circle */circle: Circle (double t_x, double t_y, double t_r): baseellipse (t_x, t_y) {r = t_r;} circle: Circle (const baseellipse & Ba, double t_r): baseellipse (BA) {r = t_r ;} void circle: Area () const {cout <pI * r <Endl;}/* Oval */ellipse: ellipse (double
T_x, double t_y, double T_A, double T_ B): baseellipse (t_x, t_y) {A = T_A; B = T_ B;} ellipse: ellipse (const baseellipse & Ba, double T_A, double T_ B): baseellipse (BA) {A = T_A; B = T_ B;} void ellipse: Area () const {cout <0.5 * a * B <Endl;} int main () {circle C1 (, 5); c1.move );
C1.area (); ellipse E1 (0, 0, 7, 8); e1.move (3, 4); e1.area (); Return 0 ;}

 

Related Article

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.