"C + + lesson Tenth"---inheritance and polymorphism

Source: Internet
Author: User

One, the rewrite of the function

What is a function rewrite? The same type of function that is defined in the subclass and in the parent class is called the override of the function, note the difference between the function override and the function overload.

The introduction of the problem: so what if the rewrite of the function occurs, how does the compiler parse it?

To solve this problem, we first have to figure out what a function rewrite is, and the following examples illustrate:

1. Define the same function in the subclass as the prototype in the parent class

2. Function overrides occur only between the parent and child classes

#include <iostream> using namespace Std;class parent{public       :              void print ()              {                     cout<< " Voidparent::p rint () ...  "<<endl;                 }    ; Class Child:public parent{public       :              void print ()              {                     cout<< "Voidchild::p rint ()  ... "<<endl;                  }           ; int main (int argc, char **argv) {       childchild;       Child.print ();         Child. Parent::p rint ();       Cin.get ();       Return0;} What the above example prints: void Child::p rint () ...  void Parent::p rint () ...  


This leads to the conclusion that:

1. The overridden function in the parent class is still inherited to the subclass

2. By default, functions overridden in the class will hide functions in the parent class

3. Through the scope resolution:: Can access the hidden function in the parent class

Second, now that the function rewrite is going on, so now the second question, when our function overrides encountered the assignment compatibility principle, what should we do?

such as the following program will output what content?

#include <iostream> using namespace Std;class parent{public       :              void print ()              {                     cout<< " Voidparent::p rint () ...  "<<endl;                 }    ; Class Child:public parent{public       :              void print ()              {                     cout<< "Voidchild::p rint ()  ... "<<endl;                  }           ; int main (int argc, char **argv) {       childchild;   Parent parent;   Parent *P1 = &child;   Parent *p2 = &parent;        parent& P3 = child;   parent& P4 = parent;    P1->print ();   P2->print ();       P3.print ();   P4.print ();               Cin.get ();       Return0;}


To know the answer, we also need to understand the compiler's behavior:

1.c++ is the same as C, it is a statically compiled language

2. At compile time, the compiler automatically determines what kind of object is pointed to by the type of pointer

3. So the compiler thinks the parent pointer is pointing to the parent class object (which is reasonable based on the assignment compatibility principle)

4. Because the program is not running, it is not possible to know whether the parent pointer points to a parent class object or a Subclass object

5. From the point of view of program security, the compiler assumes that the parent pointer only points to the parent class object, so the result of the compilation is to call the member function of the parent class

Looking at the above description, I think the answer is clear, for security reasons, then the output is:

void Parent::p rint ().  void Parent::p rint () ...  void Parent::p rint () ...  void Parent::p rint ()  ...


Third, so the above results make us want, we clearly assigned a subclass object, but point to the parent class object, then what is the solution?

The results we need:

1. Judging the invocation of an overriding function based on the actual object type

2. Call a function defined in the parent class if the parent pointer is pointing to a parent class object

3. If the parent pointer is to a child class object, the overriding function defined in the subclass is called

Polymorphism in object-oriented

1. Determine the specific invocation target of a function invocation statement based on the actual object type

2. Polymorphism: The same invocation statement has many different forms of expression


P point to subclass object

So, how is polymorphism implemented in C + +? Let's look at the nature of polymorphism.

Support for polymorphism with the virtual keyword in 1.c++

2. A function that uses virtual declarations can be overridden to show polymorphic properties

Yes, that's the legendary virtual function.

So here's an improvement to the above function, as follows:

#include <iostream> using namespace Std;class parent{public       :              virtual void print ()              {                     cout< < "Voidparent::p rint () ...  "<<endl;                 }    ; Class Child:public parent{public       :              virtual void print ()              {                     cout<< "Voidchild::p rint ()  ... "<<endl;                  }           ; int main (int argc, char **argv) {       childchild;   Parent parent;   Parent *P1 = &child;   Parent *p2 = &parent;        parent& P3 = child;   parent& P4 = parent;    P1->print ();   P2->print ();       P3.print ();   P4.print ();               Cin.get ();       Return0;} Look at what's printed: void Child::p rint () ...  void Parent::p rint () ...  void Child::p rint () ...  void Parent::p rint ()  ... This is in line with our expectations.


Four, before we have always mentioned to distinguish the concept of overloading and rewriting, then what is the difference between overloading and rewriting?

Here's a list of the differences:

function overloading

1. Must be in the same class

2. Subclasses cannot overload a parent class function, the parent class with the same name will be overwritten

3. Overloading is the invocation of a function at compile time, depending on the type and number of arguments

function rewriting

1. Must occur between the parent class and the child class

2. And the parent class must have exactly the same prototype as the function in the child class

3. After using virtual declaration, you can generate polymorphic

4. Polymorphism is the invocation of a function depending on the type of object at run time

The concept is clearly stated, so look at an example

#include <iostream> using namespace Std;class parent{public:virtual void print () { cout<< "Parent::p rint () ...                 "<<endl; } virtual void print (int i) {cout<< "Parent::p rint (inti) ...                   "<<endl; } virtual void print (int i,int j) {cout<< "Parent::p rint (inti,int J) ...                   "<<endl;                     }};class child:public parent{public:virtual void print (int i,int j) { cout<< "Child::p rint (Inti,int j) ...                    "<<endl; } virtual void print (int i,int j,int k) {cout<< "Child::p rint (inti , int j,int k) ...                    "<<endl;   }};int Main (int argc, char **argv) {child child;  (Child.print); Achieve polymorphic Child.print (1, 2, 3);//Call the member function in the subclass Child.print (1);       Error, because the parent class member function is overwritten cin.get (); Return0;}


The main function is explained very clearly, because the parent class will be covered by the quilt, without overloading, so error.

V. Some of the conceptual things about polymorphism have been explained, the following is a deep understanding of virtual functions, the implementation principle of polymorphism in C + +

1. When a virtual function is declared in a class, the compiler generates a virtual function table in the class

2. Virtual function table is a data structure for storing virtual member function pointer of a class

3. Virtual function tables are automatically generated and maintained by the compiler

The 4.virtual member function is placed in the virtual function table by the compiler

5. When a virtual function exists, each object has a pointer to the virtual function table

This is a model diagram created by a virtual function table

There is no doubt that calling an overriding function through the virtual function table pointer vptr is done when the program is running, so you need to address the function to determine what functions should actually be called. The normal member function is a function that determines the call at compile time. In efficiency, the efficiency of virtual function is much lower. For efficiency reasons, it is not necessary to declare all member functions as virtual functions.

Now another question: When is the vptr pointer in the object initialized?

1. The object is initialized by the compiler when it is created by the vptr pointer.

2. Only when the object's construction is completely finished, Vptr's point is finalized.

3. Vptr of Parent class object to parent virtual function table

4. Sub-class object Vptr point to sub-class virtual function table

Therefore, the call virtual function in the constructor is not possible to implement polymorphism.

Here is a try to know, no longer an example:

Six, the last to see a pure virtual function

In projects where virtual functions and pure virtual functions are often used, what is going on?

Abstract concepts in Object-oriented

There are some abstract concepts when it comes to object-oriented analysis! That is, the concept of a non-existent, such as asking you to ask for a graphic area, but do not tell you what graphics, then how to ask? The design of this object completely divorced from the actual, no meaning! As follows:

Class shape{public       :              Virtual double area () = 0;};


This is the format of the pure virtual function

How does that make him meaningful? Then this is going to be implemented in our inheritance class, for example:

Class Rectangle:public shape{       private:              double r_a;              Double R_b;       Public:              Rectangle (int a, int b)              {                     r_a= A;                     r_b= b;               }                  Virtual double area ()              {                     return ((r_a) * (R_b));}                    ;


After a preliminary attempt to use the pure virtual function, a deep step to understand the pure virtual function

Abstract classes in object-oriented

1. Abstract classes can be used to represent abstract concepts in the real world

2. An abstract class is a class that can only define a type and not produce an object

3. Abstract classes can only be inherited and overridden by related functions

4. The direct feature of abstract class is pure virtual function

A pure virtual function is a virtual function that only declares a function prototype and deliberately does not define a function body.

Abstract classes and pure virtual functions

1. Abstract classes cannot be used to define objects

2. Abstract classes can only be used to define pointers and references

3. Pure virtual function in abstraction must be overridden by a quilt class

The above area is a pure virtual function, = 0 tells the compiler that this function deliberately declares only that it is undefined.

Finally, let's look at an example of a pure virtual function implementation:

#include <iostream> using namespace Std;class shape{public       :              Virtual double area () = 0;}; class Rectangle: Public shape{       Private:              double r_a;              Double R_b;       Public:              Rectangle (int a, int b)              {                     r_a= A;                     r_b= b;               }                  Virtual double area ()              {                     return ((r_a) * (R_b));}                    ; Class Circle:public shape{       private:              double c_r;       Public:              Rectangle (int r)              {                     c_r= R;              }                  Virtual double area ()              {                     return (3.14 * (c_r) * (C_r));}                   ; void Area (shape* s) {   cout<<s->area () <<endl;} int main (int argc, char **argv) {       Rectanglerect ( 10, 5); Circle Circle (5);       Cin.get ();       Return0;}


That's what we're talking about. The implementation in the sub-class is consistent.

Seven, summarize:

1. Function rewriting is an object-oriented scenario that is likely to occur

2. Function overrides can only occur between the parent class and the child class

3. The specific function of the call needs to be determined based on the type of actual object

The 4.virtual keyword is the only way to support polymorphism in C + +

5. The overridden virtual function can exhibit polymorphic characteristics

6. Function overloading differs from function rewriting

7. Polymorphism is achieved through a virtual function table

8. Virtual functions are affected by efficiency

9. Abstract classes can be used to represent abstract concepts in the real world

10. Abstract classes are implemented by pure virtual functions

"C + + lesson Tenth"---inheritance and polymorphism

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.